Java Streams: group a List into a Map of Maps

前端 未结 3 1307
粉色の甜心
粉色の甜心 2020-12-14 01:30

How could I do the following with Java Streams?

Let\'s say I have the following classes:

class Foo {
    Bar b;
}

class Bar {
    String id;
    Str         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 01:44

    You can group your data in one go assuming there are only distinct Foo:

    Map> map = list.stream()
            .collect(Collectors.groupingBy(f -> f.b.id, 
                     Collectors.toMap(f -> f.b.date, Function.identity())));
    

    Saving some characters by using static imports:

    Map> map = list.stream()
            .collect(groupingBy(f -> f.b.id, toMap(f -> f.b.date, identity())));
    

提交回复
热议问题