以下代码按预期编译:
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()
以vararg作为参数。因此,它需要几个对象或对象数组,并将这些对象存储在列表中。
您正在传递一个HashSet作为参数。因此,此HashSet存储在列表中,因此最终得到一个包含单个HashSet的列表。
要将Set转换为List,请使用new ArrayList<>(set)
。或者,不要将其转换为列表,因为这是不必要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句