使用Java8中的流将集合收集到HashSet中会导致“类型不匹配”错误。

4
以下代码按预期编译:
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));
}

1
在这两种情况下,List 的创建都是完全无用的。在第一个示例中,只需使用Arrays.stream(tt)来流式处理数组元素,在第二个示例中,使用tt.stream()来流式处理HashSet的元素。当然,map(s -> s) 步骤也毫无意义... - Holger
1个回答

4

这是预期的行为。Arrays.asList()以可变参数作为参数。因此,它期望多个对象或对象数组,并将这些对象存储在列表中。

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接