Collectors.toSet()
不保留顺序。我可以改用列表,但我想指出生成的集合不允许元素重复,这正是 Set
接口(interface)的用途。
最佳答案
您可以使用 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]
}
}
关于java - 是否有收集器收集到保序集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27611896/