以下代码按预期编译:
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));
}
List
的创建都是完全无用的。在第一个示例中,只需使用Arrays.stream(tt)
来流式处理数组元素,在第二个示例中,使用tt.stream()
来流式处理HashSet
的元素。当然,map(s -> s)
步骤也毫无意义... - Holger