使用Collector.toMap

时间:2019-03-18 02:24:41

标签: java collections java-stream

我无法解决一个简单的问题。 我有一个类型为X的地图,需要将其转换为类型为Y的地图

mapOfTypeX.entrySet().stream().map(e-> transform(e)).collect(Collector.toMap(....));

transform函数获取条目集并返回Y类型的Map,例如Map<key,SomeClassObjectAsValue>

public Map<key,SomeClassObjectAsValue> transform(Map.Entry<String,Person> entry){}

我不确定要传递给Collector.ToMap函数的内容。现有代码是命令性代码,它将Y类型的映射传递到转换函数并执行map.putall

2 个答案:

答案 0 :(得分:1)

基本上,您需要使用collect函数而不是使用toMap包装器。

mapOfTypeX.entrySet().stream()
          .map(e-> transform(e))
          .collect(HashMap::new, HashMap::putAll, HashMap::putAll);

答案 1 :(得分:1)

您可以使用flatMap个流,并将从transform方法接收的所有映射中的所有条目合并为:

Map<key,SomeClassObjectAsValue> newMap = 
    mapOfTypeX.entrySet()
        .stream()
        .flatMap(e -> transform(e).entrySet().stream())
        .collect(Collectors
            .toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue));