Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java lambda to build map from two maps

I have some code that I need help with ... I'm trying to build a map using two maps as a source and at the same time using java lambdas

Map<String, List<String>> motorsMapping = new HashMap<>();

motorsMapping.put("CAR", Collections.singletonList("AUDI"));
motorsMapping.put("CAR_AND_BIKE", Arrays.asList("AUDI", "BMW"));
motorsMapping.put("BIKE", Collections.singletonList("BMW"));

Map<String, List<String>> models = new HashMap<>();
models.put("AUDI", Arrays.asList("A1", "Q2"));
models.put("BMW", Arrays.asList("X1", "X5"));


motorsMapping.keySet().forEach(key -> {
     Map<String, List<String>> result = new HashMap<>();
     result.put(key, new ArrayList<>());
     motorsMapping.get(key).forEach(value -> models.getOrDefault(value, Collections.emptyList()).forEach(property -> result.get(key).add(property)));
});

I can do that with the foreach that you can see above but I was trying to do it using lambdas ... something like this

Map<String, List<String>> collected = motorsMapping
    .entrySet()
    .stream()
    .map(entry -> {
        return entry.getValue()
            .stream()
            .map(key -> models.getOrDefault(key, Collections.emptyList()))
            .flatMap(List::stream)
            .collect(Collectors.groupingBy(entry.getKey(), Collectors.toList()));
    }
)...

My desired output would be something like

CAR -> A1, Q2
BIKE -> X1, X5
CAR_AND_BIKE -> A1, Q2, X1, X5

But I cannot get my head around it

like image 248
F R Avatar asked Aug 21 '19 15:08

F R


1 Answers

As you've tagged this question under java-8 I'm assuming you have Java 8 and don't have access to flatMapping in Java 9. In java-8 you can do following using :Collectors.toMap

Map< String, List< String > > collected = motorsMapping.entrySet( )
            .stream( )
            .collect( Collectors.toMap( Map.Entry::getKey
                    , motorMap -> motorMap.getValue( )
                                    .stream( )
                                    .flatMap( value -> models.get( value ).stream( ) )
                                    .collect( Collectors.toList( ) ) ) );
collected.entrySet( ).stream( ).forEach( System.out::println );

Here's the output:

CAR_AND_BIKE=[A1, Q2, X1, X5]
CAR=[A1, Q2]
BIKE=[X1, X5]
like image 118
stackFan Avatar answered Nov 10 '22 14:11

stackFan