Collectors.toSet() 不保留订单 . 我可以使用Lists代替,但我想指出结果集合不允许元素重复,这正是 Set 接口的用途 .
Collectors.toSet()
Set
您可以使用 toCollection 并提供所需集的具体实例 . 例如,如果要保留插入顺序:
toCollection
Set<MyClass> set = myStream.collect(Collectors.toCollection(LinkedHashSet::new));
例如:
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] } }
1 回答
您可以使用
toCollection
并提供所需集的具体实例 . 例如,如果要保留插入顺序:例如: