Java 是否有收集到保留顺序的集合的收集器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27611896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Collector that collects to an order-preserving Set?
提问by gvlasov
Collectors.toSet()
does not preserve order. I could use Lists instead, but I want to indicate that the resulting collection does not allow element duplication, which is exactly what Set
interface is for.
Collectors.toSet()
不保持秩序。我可以改用 Lists,但我想指出生成的集合不允许元素重复,这正是Set
接口的用途。
采纳答案by Alexis C.
You can use toCollection
and provide the concrete instance of the set you want. For example if you want to keep insertion order:
您可以使用toCollection
并提供所需集合的具体实例。例如,如果您想保持插入顺序:
Set<MyClass> set = myStream.collect(Collectors.toCollection(LinkedHashSet::new));
For example:
例如:
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]
}
}