0

How can I convert List<Map<String,Object>> to Map<String,Map<String,Object>> in java while keeping the key for outer map similar to inner Map.

For example:

The record

<1:{String1,Object1}, 2:{String2,Object2}, ...> 

should be converted to

<{String1 :{String1, Object1}}, {String2:{String2,Object2}}, ...>.

Are there any Java APIs for doing this quite easily?

Eran
395k57 gold badges725 silver badges792 bronze badges
asked Jan 22, 2018 at 10:11
1

1 Answer 1

1

This will create a Map where each entry corresponds to a Map<String,Object> of the input List - the key is the "first" key of the Map<String,Object> (according to iteration order) and the value is the Map<String,Object> itself.

It assumes that each Map<String,Object> of the input List has at least one entry, and that the keys of all the input Maps are distinct. If these assumptions are incorrect, this code will throw an exception.

Map<String,Map<String,Object>> map = 
 list.stream()
 .collect(Collectors.toMap(m -> m.keySet().iterator().next(),
 Function.identity()));
answered Jan 22, 2018 at 10:22
1
  • @nirajdighe read the Javadoc of the relevant classes and interfaces. Commented Jan 23, 2018 at 7:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.