Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating map from list of objects having a map using java lambda8

I've an object,

class Object2{
     String name;
     String id;
     Map<String, String> customData;
}

class Object1{
     List<Object2> obj1List;
}

I want to convert this customData Map in the List of object1 into one single map, I am ok with over-writing the values if the key already exists.

like image 855
sar Avatar asked Dec 05 '18 23:12

sar


2 Answers

Here's a way with lambdas and Java 8:

Map<String, String> map = new LinkedHashMap<>();
object1List.forEach(o1 -> 
        o1.getObject1List().forEach(o2 -> map.putAll(o2.getCustomData())));
like image 124
fps Avatar answered Oct 20 '22 17:10

fps


Use flatMap and toMap as follows:

List<Object1> source = ...
Map<String, String> result = 
     source.stream()
           .flatMap(e -> e.getObj1List().stream()
                               .flatMap(a -> a.getCustomData().entrySet().stream()))
           .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (l, r) -> r));

or if you're dealing with a single Object1 object:

Object1 myObj = ...
Map<String, String> result = 
      myObj.getObj1List()
           .stream()
           .flatMap(a -> a.getCustomData().entrySet().stream())
           .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (l, r) -> r));
like image 30
Ousmane D. Avatar answered Oct 20 '22 19:10

Ousmane D.