Consider these two classes
Subject 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,...
}
Observer class:
class Observer{
long id;
Subject subject;
public Observer(long id,Subject subject){
this.id=id;
this.subject=subject;
}
// getters, setters, toString,...
}
And consider this list of observers
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));
What i have tried so far and succeeded to do it is to group observers by subject as follow
Map<Subject, List<Observer>> observersGroupedBySubject = observers.stream().collect(
Collectors.groupingBy(Observer::getSubject));
But how can i group observers by subject's category using the same above logic (Collectors
, groupingBy
, method reference
,...)?
For instance, how can i get observers that subscribed to a subject whose category equals to sport
using something like this
Map<String, List<Observer>> observersGroupedBySubjectCategory = ...;
observersGroupedBySubjectCategory.get("sport");
Thanks.
Use
Collectors.groupingBy(o -> o.getSubject().getCategory())
or define getSubjectCategory()
in Observer
class and use method reference:
Collectors.groupingBy(Observer::getSubjectCategory)
But how can i group observers by subject's category using the same above logic (Collectors, groupingBy, method reference,...)?
As I explained here (the second part), you just need to provide a function that will take the subject's category for a given observer. So in this case it will be:
groupingBy(o -> o.getSubject().getCategory())
This will give you a Map<String, List<Observer>>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With