gvl*_*sov 102 java java-8 collectors
Collectors.toSet()不保留秩序.我可以使用Lists代替,但我想指出结果集合不允许元素重复,这正是Set接口的用途.
Ale*_* C. 194
您可以使用toCollection并提供所需集合的具体实例.例如,如果要保留插入顺序:
Set<MyClass> set = myStream.collect(Collectors.toCollection(LinkedHashSet::new));
Run Code Online (Sandbox Code Playgroud)
例如:
public class Test {
public static final void main(String[] args) {
List<String> list = Arrays.asList("b", "c", "a");
Set<String> linkedSet =
list.stream().collect(Collectors.toCollection(LinkedHashSet::new));
Set<String> collectorToSet =
list.stream().collect(Collectors.toSet());
System.out.println(linkedSet); //[b, c, a]
System.out.println(collectorToSet); //[a, b, c]
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22241 次 |
| 最近记录: |