Dynamic grouping by specific attributes with Collection.stream

后端 未结 2 2111
Happy的楠姐
Happy的楠姐 2020-12-15 11:57

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         


        
2条回答
  •  一整个雨季
    2020-12-15 12:14

    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, List> with functions of the type U -> Object.

提交回复
热议问题