Java Streams: group a List into a Map of Maps

前端 未结 3 1296
粉色の甜心
粉色の甜心 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条回答
  • 2020-12-14 01:44

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

    Map<String, Map<String, Foo>> 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<String, Map<String, Foo>> map = list.stream()
            .collect(groupingBy(f -> f.b.id, toMap(f -> f.b.date, identity())));
    
    0 讨论(0)
  • 2020-12-14 01:49

    Suppose (b.id, b.date) pairs are distinct. If so, in second step you don't need grouping, just collecting to Map where key is foo.b.date and value is foo itself:

    Map<String, Map<String, Foo>> map = 
           myList.stream()
                 .collect(Collectors.groupingBy(f -> f.b.id))    // map {Foo.b.id -> List<Foo>}
                 .entrySet().stream()
                 .collect(Collectors.toMap(e -> e.getKey(),                 // id
                                           e -> e.getValue().stream()       // stream of foos
                                                 .collect(Collectors.toMap(f -> f.b.date, 
                                                                           f -> f))));
    

    Or even more simple:

    Map<String, Map<String, Foo>> map = 
           myList.stream()
                 .collect(Collectors.groupingBy(f -> f.b.id, 
                                                Collectors.toMap(f -> f.b.date, 
                                                                 f -> f)));
    
    0 讨论(0)
  • 2020-12-14 01:52

    An alternative is to support the equality contract on your key, Bar:

    class Bar {
        String id;
        String date;
    
        public boolean equals(Object o){
           if (o == null) return false;
           if (!o.getClass().equals(getClass())) return false;
           Bar other = (Bar)o;
           return Objects.equals(o.id, id) && Objects.equals(o.date, date);
        }
    
        public int hashCode(){
           return id.hashCode*31 + date.hashCode;
        }    
    }
    

    Now you can just have a Map<Bar, Foo>.

    0 讨论(0)
提交回复
热议问题