7

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?

bartektartanus
  • 15,284
  • 6
  • 74
  • 102

3 Answers3

9

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;

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    Assuming Java8, and 1-to-1 match of all int keys in each map. (Not that mines any better at avoiding that) =P – Adam Yost Jun 03 '14 at 14:46
1

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);
}
pasha701
  • 6,831
  • 1
  • 15
  • 22
0

If the maps were the same type, you could use a putAll(), but since you are changing the key value pairs, it looks like you are going to have to iterate over each integer, get() from each map, then put(mapOneVal,mapTwoVal)

for(int i=0;i<max;i++){
    String key = mapOne.get(i);
    Double val = maptwo.get(i);
    if(key!=null && val!=null)
        map3.put(key,val);
}
Adam Yost
  • 3,616
  • 23
  • 36
  • 1
    This could potentially lead to a lot of misses, if the maps have gaps in the sequence. – Erik Madsen Jun 03 '14 at 14:37
  • It could, and that can be easily null checked. Otherwise its a matter of iterating over mapone.keySet() and mapTwo.keySet() separately, then combining the answer. – Adam Yost Jun 03 '14 at 14:40