【问题标题】:Collect map from other map by stream [duplicate]通过流从其他地图收集地图[重复]
【发布时间】:2019-08-30 14:05:07
【问题描述】:

我有这样的代码:

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)));

【问题讨论】:

标签: java dictionary java-8 functional-programming java-stream


【解决方案1】:

有可能,你只是犯了一个小语法错误……

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

【讨论】:

    【解决方案2】:

    是的,你可以在纯 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))...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多