按流从其他地图收集地图

时间:2019-08-30 14:05:07

标签: java java-8 java-stream

我有这样的代码:

Map<Integer, Settings> operatorsSettings = new HashMap<>();
operators.forEach((operator, codeTypes) -> operatorsSettings.put(operator, mapper.convertValue(codeTypes.get(SETTINGS), Settings.class)));
return operatorsSettings;

我写了,但我想知道。是否可以在不创建新地图的情况下编写它。这样的东西(错误的代码):

return operators.entrySet().stream()
        .collect(entry -> Collectors.toMap(entry.getKey() , mapper.convertValue(entry.getValue().get(SETTINGS), Settings.class)));

2 个答案:

答案 0 :(得分:1)

是的,您可以在纯Java中执行此操作:

return operators.entrySet().stream()
    .collect(Collectors.toMap(entry -> entry.getKey() , entry -> mapper.convertValue(entry.getValue().get(SETTINGS), Settings.class)));

或者您可以使用streamex库并像这样编写它:

EntryStream.of(operatorsSettings).mapValues(codeTypes -> mapper.convertValue(codeTypes.get(SETTINGS), Settings.class))...

答案 1 :(得分:1)

有可能,您只是犯了一个小语法错误...

return operators.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey() , mapper.convertValue(entry.getValue().get(SETTINGS), Settings.class)));