Java 8 - 流转换地图的值类型

J.D*_*one 5 java

我想将类型转换List<A>List<B>.我可以用java 8流方法吗?

    Map< String, List<B>> bMap = aMap.entrySet().stream().map( entry -> {
        List<B> BList = new ArrayList<B>();
        List<A> sList = entry.getValue();
        // convert A to B
        return ???; Map( entry.getKey(), BList) need to return
    }).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
Run Code Online (Sandbox Code Playgroud)

我尝试使用此代码,但无法在map()中进行转换.

Pel*_*cho 10

如果我理解正确你有一个Map<String, List<A>>,你想将它转换为Map<String, List<B>>.你可以这样做:

Map<String, List<B>> result = aMap.entrySet().stream()
    .collect(Collectors.toMap(
        entry -> entry.getKey(),                        // Preserve key
        entry -> entry.getValue().stream()              // Take all values
                     .map(aItem -> mapToBItem(aItem))   // map to B type
                     .collect(Collectors.toList())      // collect as list
        );
Run Code Online (Sandbox Code Playgroud)


Dar*_*hta 8

您可以AbstractMap.simpleEntrymap函数中实例化并执行转换。

例如,以下代码转换List<Integer>List<String>

Map<String, List<Integer>> map = new HashMap<>();
Map<String, List<String>> transformedMap = map.entrySet()
    .stream()
    .map(e -> new AbstractMap.SimpleEntry<String, List<String>>(e.getKey(), e.getValue().stream().map(en -> String.valueOf(en)).collect(Collectors.toList())))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)

  • 难道只通过在“toMap”中进行转换就可以避免使用“SimpleEntry”吗? (2认同)