Search code examples
javajava-8java-streamcollectors

How to group a object list into a map and select the first object of different type for each key using a Java stream?


I have data like: List<Object1> list1.

I need to convert it to Map<String, Object2> map1.

Code below

map1=list1.stream()    
.collect(Collectors  
.groupingBy(Object1::getCity,Collectors  
.mapping(p -> new Object2(p.getvalue1(),p.getvalue2(),p.getvalue3()),  

Here I want to get the first(based on any user defined method) item of Object1 type corresponding to each key));

e.g.

[
 {name:a,roll:2,id:3,age:24,city:goa},  
 {name:b,roll:3,id:3,age:24,city:Delhi},  
 {name:c,roll:2,id:1,age:27,city:goa}
]

Result:

{  
  id=3:{name:a,city:goa},
  id=1:{name:c,city:goa} 
}

Solution

  • You can use Collectors.toMap and define the merge function to take first one for each key.

    Map<String, Object2> map = 
         list1.stream()
              .collect(Collectors.toMap(Object1::getCity,
                              p -> new Object2(p.getvalue1(),p.getvalue2(),p.getvalue3())
                              (a, b) -> a));