Home > database >  Convert List of Maps to a single Map with VAVR
Convert List of Maps to a single Map with VAVR

Time:10-05

I'm struggling to reduce a List of Maps to a single Map using Vavr

<List<Map<String, Object>>>

to

<Map<String, Object>>

I tried it with flatmap/reduce/merge but unfortunately with no happy end :-(

Can someone provided an example how to do it with io.vavr.collection.List/io.vavr.collection.Map ?

CodePudding user response:

I have no idea what vavr has to do with this.

list.stream()                             // A
  .flatMap(map -> map.entrySet().stream()) // B
  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

[A] Now you have a stream of Map<String, Object>.

[B] Now you have a stream of map entries. Now you have a stream of key/value pairs.

Then just collect them into a map by providing a function to extract a key from a Map.Entry object, and a function that extracts a value.

Note that if you have a map of type Map<String, Object>, I give it 99% odds you're doing something wrong. Java is nominally, statically, and strongly typed, after all.

CodePudding user response:

You have several options.

For instance, given the following data set (sorry for its simplicity):

Map<String, Object> map1 = HashMap.of("key1", "value1", "key2", "value2");
Map<String, Object> map2 = HashMap.of("key3", "value3", "key4", "value4");
Map<String, Object> map3 = HashMap.of("key5", "value5", "key6", "value6");
List<Map<String, Object>> list = List.of(map1, map2, map3);

You can combine the different Maps with fold, for instance:

Map<String, Object> result = list.fold(HashMap.empty(), (m1, m2) -> m1.merge(m2));

You can use reduce as well:

Map<String, Object> result = list.reduce((m1, m2) -> m1.merge(m2));

Both of them use the Map merge method.

  • Related