Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two maps by key

Tags:

java

merge

join

map

I have two maps:

Map<Integer, String> mapOne = {(1,"a"), (2, "b")};
Map<Integer, Double> mapTwo = {(1,10.0), (2,20.0)};

and I want to combine this maps into one by Integer value, so the result map is

Map<String, Double> mapResult = {("a",10.0), ("b",20.0)};

Is there any way to do this easier than iterate over entry set?

like image 665
bartektartanus Avatar asked Jun 03 '14 14:06

bartektartanus


People also ask

How do I merge two maps together?

Alternatively, we can use Stream#concat() function to merge the maps together. This function can combine two different streams into one. As shown in the snippet, we are passed the streams of map1 and map2 to the concate() function and then collected the stream of their combined entry elements.

Can you combine two maps in Minecraft?

You can't merge maps. The only way to fully explore a map is to manually explore all the terrain shown on the map while holding that map.


2 Answers

Assuming that the keys of the two maps match and that the maps have the same number of entries, with Java 8 you can write it in one line with:

Map<String, Double> map = mapOne.entrySet().stream()
                            .collect(toMap(e -> e.getValue(),
                                           e -> mapTwo.get(e.getKey())));

So you start from the first map and create a new map where the keys are the values of mapOne and the values are the corresponding values in mapTwo.

Technically this is somewhat equivalent to iterating over the entry set of the first map though.

Note: requires import static java.util.stream.Collectors.toMap;

like image 105
assylias Avatar answered Sep 28 '22 10:09

assylias


Looks like only iteration:

@Test
public void testCollection() {
    Map<Integer, String> mapOne = new HashMap<Integer, String>();
    mapOne.put(1, "a");
    mapOne.put(2, "b");
    Map<Integer, Double> mapTwo = new HashMap<Integer, Double>();
    mapTwo.put(1, 10.0);
    mapTwo.put(2, 20.0);


    Map<String, Double> mapResult = new HashMap<String, Double>();
    Set<Integer> keySet = mapOne.keySet();
    keySet.retainAll(mapTwo.keySet());
    for (Integer value : keySet) {
        mapResult.put(mapOne.get(value), mapTwo.get(value));
    }
    System.out.println(mapResult);
}
like image 22
pasha701 Avatar answered Sep 28 '22 09:09

pasha701