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
  • 387,369
  • 54
  • 702
  • 768

1 Answers1

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()));
Eran
  • 387,369
  • 54
  • 702
  • 768