Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collectors groupingBy java 8

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.

like image 790
MChaker Avatar asked Jan 09 '23 10:01

MChaker


2 Answers

Use

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

or define getSubjectCategory() in Observer class and use method reference:

Collectors.groupingBy(Observer::getSubjectCategory)
like image 59
Alex Salauyou Avatar answered Jan 12 '23 22:01

Alex Salauyou


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>>.

like image 41
Alexis C. Avatar answered Jan 12 '23 22:01

Alexis C.