Skip to content
Advertisement

How to convert an array of map into a map in JAVA8?

Right now I have

Map<String, String>[] map_array= [
{"k":"k1", "v":"v1"},
{"k":"k2", "v":"v2"}
]

How to use JAVA8 stream to convert it into

Map<String, String> map = {"k1" : "v1", "k2" : "v2"}

Update: Sorry I was being unclear. The map_array contains two maps, and each map has two entries with the first one being key as “k”, value as “k1” and second entry being key as “v” and value as “v1”. Now I’m trying to merge them into one ImmutableMap<String, String> with key being “k1/k2” and value being “v1/v2”. The implementation I have right now works, but I’m wondering if there’s any cleaner way in JAVA8. Below is my implementation:

(Map<String, String> m : map_array) {
resault_map.put(m.get("k"), m.get("v"));
}
return result_map;

Advertisement

Answer

It seems like each map in the array represents a key-value pair in the resulting map. Therefore, you can use Collectors.toMap, which accepts to functions – one that transforms an array element to the KVP’s key, and one that that transforms an array element to the KVP’s value:

public static Map<String, String> mapArraysToMap(Map<String, String>[] mapArray) {
    return Arrays.stream(mapArray).collect(Collectors.toMap(
        x -> x.get("k"),
        x -> x.get("v")
    ));
}

This is assuming that all array elements have a k and v key. You might want to filter out those that don’t if that is possible in your scenario.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement