Using Java lambda to build map from two maps

F R*_*F R 7 java lambda java-8 java-stream collectors

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)));
});
Run Code Online (Sandbox Code Playgroud)

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()));
    }
)...
Run Code Online (Sandbox Code Playgroud)

My desired output would be something like

CAR -> A1, Q2
BIKE -> X1, X5
CAR_AND_BIKE -> A1, Q2, X1, X5
Run Code Online (Sandbox Code Playgroud)

But I cannot get my head around it

sta*_*Fan 3

正如您在下面标记的这个问题,java-8我假设您有 Java 8 并且无权访问flatMappingJava 9。java-8您可以使用以下命令执行以下操作: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 );
Run Code Online (Sandbox Code Playgroud)

这是输出:

CAR_AND_BIKE=[A1, Q2, X1, X5]
CAR=[A1, Q2]
BIKE=[X1, X5]
Run Code Online (Sandbox Code Playgroud)