I am trying to group a list of objects by mulitple attributes, by using Java 8 Collection-Stream.
This works pretty well:
public class MyClass
{
p
Instead of list of names, you could also consider supplying a list of functions (with one mandatory) to group your elements.
These functions should map an element of MyClass
to an object, so you can use Function
.
private static Map, List> groupListBy(List data, Function mandatory, Function... others) {
return data.stream()
.collect(groupingBy(cl -> Stream.concat(Stream.of(mandatory), Stream.of(others)).map(f -> f.apply(cl)).collect(toList())));
}
And some example of calls:
groupListBy(data, m -> m.type); //group only by type
groupListBy(data, m -> m.type, m -> m.module); //group by type and by module
Of course you can make this method generic so that it returns a Map
with functions of the type , List>
U -> Object
.