收藏家分组 java 8

Collectors groupingBy java 8

考虑这两个 classes

主题 class:

class Subject{
    long id;
    String category;
    String description;
    public Subject(long id,String category,String description){
        this.id=id;
        this.category=category;
        this.description=description;
    }
    // getters, setters, toString,...    
}

观察者class:

class Observer{
    long id;
    Subject subject;
    public Observer(long id,Subject subject){
        this.id=id;
        this.subject=subject;
    }
    // getters, setters, toString,...
}

并考虑这份观察员名单

Subject s1 = new Subject(1, "sport", "subject 1");
Subject s2 = new Subject(2, "music", "subject 2");
Subject s3 = new Subject(3, "sport", "subject 3");

List<Observer> observers = Arrays.asList(new Observer(1, s1),
        new Observer(2, s1), new Observer(3, s2), new Observer(4, s3));

到目前为止我已经尝试并成功做到的是将观察者按主题分组如下

Map<Subject, List<Observer>> observersGroupedBySubject = observers.stream().collect(
                Collectors.groupingBy(Observer::getSubject));

但是我如何使用与上述相同的逻辑(CollectorsgroupingBymethod reference、...)按主题类别对观察者进行分组?

例如,我如何使用类似

的方法让观察者订阅类别等于 sport 的主题
Map<String, List<Observer>> observersGroupedBySubjectCategory = ...;
observersGroupedBySubjectCategory.get("sport");

谢谢。

But how can i group observers by subject's category using the same above logic (Collectors, groupingBy, method reference,...)?

正如我在 (第二部分)中所解释的那样,您只需要提供一个函数,该函数将为给定的观察者获取主题的类别。所以在这种情况下它将是:

groupingBy(o -> o.getSubject().getCategory())

这会给你一个Map<String, List<Observer>>

使用

Collectors.groupingBy(o -> o.getSubject().getCategory())

或在Observerclass中定义getSubjectCategory()并使用方法参考:

Collectors.groupingBy(Observer::getSubjectCategory)

使用过滤器。

Map<Subject, List<Observer>> observersGroupedBySubject = observers
                .stream()
                .filter((u) -> u.getSubject().getCategory()
                        .equalsIgnoreCase("sport"))
                .collect(Collectors.groupingBy(Observer::getSubject));