[英]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()
將vararg作為參數 。 因此,它需要幾個對象或一個對象數組,並將這些對象存儲在列表中。
您將一個HashSet作為參數傳遞。 所以這個HashSet存儲在一個列表中,因此你最終會得到一個包含單個HashSet的列表。
要將Set轉換為List,請使用new ArrayList<>(set)
。 或者,只是不要將其轉換為列表,因為它是不必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.