Search code examples
javajava-8hashmapjava-stream

How to map Key Value pair from one map onto another


If I have a map with the following data:

"a", "hello"
"b", "bye"
"c", "good morning"

and a second map with the following data:

"key1","a"
"key2", "b"
"key3", "c"

is it then possible to perform an operation such that I can map the value of my second map onto the key as my first map? Which would result in the final map looking like this:

"key1","hello"
"key2", "bye"
"key3", "good morning"
    

Solution

  • Apparently you want a third map made of keys from the second map, and matching values from the first map.

    Map< String , String > thirdMap = new HashMap<>() ;
    for ( Map.Entry< String , String > entry : secondMap.entrySet() ) {
        thirdMap.put(
            entry.getKey() ,                  // Second map’s key.
            firstMap.get( entry.getValue() )  // First map’s value.
        );
    }