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?
-
2Related: stackoverflow.com/questions/20363719/…Alexis C.– Alexis C.2018年01月22日 10:14:27 +00:00Commented Jan 22, 2018 at 10:14
1 Answer 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 Map
s 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()));
-
@nirajdighe read the Javadoc of the relevant classes and interfaces.Eran– Eran2018年01月23日 07:23:03 +00:00Commented Jan 23, 2018 at 7:23