在集合上使用 Java8 流收集到 HashSet 中会出现“类型不匹配”错误

Collect into a HashSet using Java8 stream over a set gives `Type Mismatch` Error

以下代码按预期编译:

import java.util.Arrays;
import java.util.HashSet;
import java.util.stream.Collectors;

public class Test2 {
    String[] tt = new String[]{ "a", "b", "c"};

    HashSet<String> bb =
        Arrays.asList(tt).stream().
        map(s -> s).
        collect(Collectors.toCollection(HashSet::new));
}

如果我将 tt 更改为 HashSet,Eclipse 编译器将失败并显示消息 Type mismatch: cannot convert from Collection<HashSet<String>> to HashSet<String>:

public class Test2 {
    HashSet<String> tt = new HashSet<String>(Arrays.asList(new String[]{ "a", "b", "c"}));

    HashSet<String> bb =
        Arrays.asList(tt).stream().
        map(s -> s).
        collect(Collectors.toCollection(HashSet::new));
}

这是意料之中的。 Arrays.asList()takes a vararg as argument。因此,它需要几个对象或一个对象数组,并将这些对象存储在一个列表中。

您正在传递一个 HashSet 作为参数。所以这个 HashSet 存储在一个列表中,因此你最终得到一个包含单个 HashSet 的列表。

要将 Set 转换为 List,请使用 new ArrayList<>(set)。或者,不要将其转换为列表,因为这没有必要。