Collecting groupBy java 8
Consider these two classes
Thematic 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 has managed to do this is to group observers by subject by following
Map<Subject, List<Observer>> observersGroupedBySubject = observers.stream().collect(
Collectors.groupingBy(Observer::getSubject));
But how can I be grouped by subject category of observers, using the same logic above ( Collectors
, groupingBy
, method reference
...)?
For example, how can I get observers who have subscribed to a topic whose category is equal sport
using something like this
Map<String, List<Observer>> observersGroupedBySubjectCategory = ...;
observersGroupedBySubjectCategory.get("sport");
Thank.
source to share
But how can I group observers by subject category using the same over logic (Collectors, groupingBy, reference method, ...)?
As I explained here (second part), you just need to provide a function that will accept a subject category for a given observer. So in this case it would be:
groupingBy(o -> o.getSubject().getCategory())
This will give you Map<String, List<Observer>>
.
source to share