SnG
SnG

Reputation: 402

Java 8: Get new map X->Z from two other maps X-> Y and Y->Z

I have two maps:

Map<String, Integer> x;
Map<Integer, String> y;

What I want is a new map, Map<String,String> where this new map has the string keys in x map to the string value in y, where those new key pair maintains the same mapping as String -> Integer -> String.

Does anyone know of a way to do this in java 8 using streams ?

Upvotes: 1

Views: 124

Answers (3)

stackFan
stackFan

Reputation: 1608

You'd have to iterate over entry set of x's entries and put y's value corresponding to x's values. There's always a chance when the value is not present in y and might return null so for such cases you can default to some value using Optional.ofNullable() on y's get() method and handle the default later. But still it's a risky way to approach given that there are chances that the size of x and y might not be same.

Example:

Map< String, Integer > x = new HashMap<>( );
x.put( "a", 1 );
x.put( "b", 2 );
x.put( "c", 3 );
Map< Integer, String > y = new HashMap<>( );
y.put( 1, "a" );
y.put( 2, "b" );
y.put( 4, "c );
Map< String, String > z  = new HashMap<>( );

if ( x.size( ) == y.size( ) ) {
 z = x.entrySet( )
    .stream( )
    .collect( 
    Collectors.toMap( Map.Entry::getKey, 
    entry -> Optional.ofNullable( y.get( entry.getValue( ) ) ).orElse( "N/A" ) ) );
}

System.out.println( z );
//prints {a=a, b=b, c=N/A}

Upvotes: 0

ernest_k
ernest_k

Reputation: 45329

An easy implementation using the first map's entry set can look like this:

Map<String, String> result = x.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> y.get(e.getValue())));

Upvotes: 2

Eugene
Eugene

Reputation: 120968

x.entrySet()
 .stream()
 .collect(Collectors.toMap(
      e -> e.getKey(),
      e -> y.get(e.getValue())
 ));

But this can fail for numerous reasons, which you could think how to solve: like what would happen is there is a value in x, but such a key is not present in y; or if there are multiple same values in x? All of these could be solved if you make your question a bit more clear.

Upvotes: 2

Related Questions