JTurk JTurk - 6 months ago 10
Java Question

Java hashmaps with Key of one as value of other

I have two maps:

map1 = <K , V>
map2 = <V, someObject>


Is there a "graceful" way of outputting a result as:

map3 = <K, someObject>


One obvious way would be to iterate over map1 and do:

for each entry in map1 {
map3.put(entry.getKey(), map2.get(entry.getValue()))
}


Ideally, I would appreciate solutions compliant with Java 7; but a clever one with Java 8 would be good for education purposes

Thanks

Answer

Here's a Java 8 method that does this:

public static <K1, K2, V> Map<K1, V> map(Map<K1, K2> first, Map<K2, V> second) {
  return first.entrySet()
    .stream()
    .filter(e -> second.containsKey(e.getValue()))
    .collect(Collectors.toMap(Map.Entry::getKey, e -> second.get(e.getValue())));
}

Add optimizations and null checks as desired.

And here's the Java 7 version:

public static <K1, K2, V> Map<K1, V> map(Map<K1, K2> first, Map<K2, V> second) {
  HashMap<K1, V> result = new HashMap<>(second.size());
  for (Map.Entry<K1, K2> entry : first.entrySet()) {
    if (second.containsKey(entry.getValue()))
      result.put(entry.getKey(), second.get(entry.getValue()));
  }
  return result;
}

I guess I even like the Java 7 version better, as it's more understandable and more honest about its cost.