如何使用 forEach 操作将 Map<String,List<String>> 转换为 Map<String,Set<String>>

Con*_*dor 1 java lambda hashmap java-8 java-stream

我想将 a 转换Map<String,List<String>>Map<String,Set<String>>优化搜索。我想出了下面的传统方法。

 for (Map.Entry<String, List<String>> entry : this.mapWithList.entrySet()) {
        Set<String> hSet = new HashSet<>(entry.getValue());
        this.mapWithSet.put(entry.getKey(), hSet);
   }
Run Code Online (Sandbox Code Playgroud)

forEach我想知道如何在Java 8中使用它。

另外,使用forEachlambda 后,代码性能会更好吗?

Ale*_*nko 5

代码性能会更好吗?

不,不会的。迭代解决方案通常性能更高。

我该如何使用forEach

Stream APIcollect()中有一个特殊的操作,旨在使用流管道的内容填充可变容器(例如,等)。文档强烈建议不要为此目的使用。当没有其他方法可以实现这一目标时,请仅考虑将其作为最后的手段。CollectionStringBuilderforEach()forEach()

为此collect(),首先您需要创建一个条目流

基于每个条目,必须创建一个新条目map(),并为此目的使用操作。静态方法Map.entry()用于实例化一个新条目。

然后collect()通过传递Collectors.toMap()参数来应用终端操作,这会根据提供的两个函数(用于值)创建一个收集器负责将流元素放入可变容器(本例中为映射)的对象) 。

main()

public static void main(String[] args) {
    Map<String,List<String>> mapWithList =
            Map.of("1", List.of("1", "2", "3"));

    Map<String,Set<String>> result =
       mapWithList.entrySet().stream()
                  .map(entry -> Map.entry(entry.getKey(),
                            new HashSet<>(entry.getValue())))
                  .collect(Collectors.toMap(Map.Entry::getKey,
                                            Map.Entry::getValue));
    System.out.println(result);
}
Run Code Online (Sandbox Code Playgroud)

输出

{1=[1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)