How to use Java 8 Collectors groupingBy to get a Map with a Map of the collection? -
imagine these classes
class subject { private int id; private type type; private string origin; private string name; subject(int id, type type, string origin, string name) { this.id = id; this.type = type; this.origin = origin; this.name = name; } // getters , setters } enum type { type1, type2 }
i have list of subject classes
list<subject> subjects = arrays.aslist( new subject(1, type.type1, "south", "oscar"), new subject(2, type.type2, "south", "robert"), new subject(3, type.type2, "north", "dan"), new subject(4, type.type2, "south", "gary"));
i result of using collectors.groupingby()
map grouping first subject
objects subject.origin
, grouped subject.type
getting result object map<string, map<type, list<subject>>>
groupingby
accepts downstream collector, can groupingby
:
subjects.stream() .collect(groupingby( subject::getorigin, groupingby(subject::gettype) ));
Comments
Post a Comment