Java Streams: group a List into a Map of Maps

前端 未结 3 1295
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题