9

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.

3 Answers 3

6

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())));
Sign up to request clarification or add additional context in comments.

1 Comment

weird naming convention in the question, but I guess you meant getObject1List()
3

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));

Comments

3

Alternatively, you can perform Stream.flatMap and then use Map.putAll as

List<Object1> object1s = new ArrayList<>(); // initialise as you would
Map<String, String> finalCustomData = new LinkedHashMap<>();
object1s.stream() // Stream<Object1>
        .flatMap(o1 -> o1.getObj1List().stream()) // Stream<Object2>
        .map(Object2::getCustomData) // Stream<Map<String, String>>
        .forEach(finalCustomData::putAll); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.