考虑这两个类
学科类:
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 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));
但是我如何使用上述相同的逻辑(Collectors
, groupingBy
, method reference
,...)按主题类别对观察者进行分组?
例如,我怎样才能让订阅者订阅一个类别等于sport
使用类似这样的主题的观察者
Map<String, List<Observer>> observersGroupedBySubjectCategory = ...;
observersGroupedBySubjectCategory.get("sport");
谢谢。