[英]How to keep order in Java 9 Set.of
I've noted while testing that the new Set.of
method of Java 9 doesn't return an ordered implementation of a Set. 我在测试时注意到Java 9的新
Set.of
方法不会返回Set的有序实现。
How can I use such utilities and still get an ordered collection? 如何使用此类实用程序并仍能获得有序的收藏集? Or there is no way, only the traditional ones?
还是没有办法,只有传统的?
Ex.: 例:
Set mySet = Set.of(new Integer[]{1, 2, 3, 4});
//mySet can come in any order when I iterate over it
EDIT 编辑
Forgot to mention, I need to keep the order that comes in the array. 忘了提,我需要保持数组中的顺序。
From the answers it seems like using the good and old new LinkedHashSet(Arrays.asList(myArr))
is still the way. 从答案来看,似乎仍然可以使用旧的
new LinkedHashSet(Arrays.asList(myArr))
。
The immutable Set
s created by Set.of
make no guarantee about the iteration order of their elements. 由
Set.of
创建的不可变Set
不能保证其元素的迭代顺序。 You could use a specific implementation that does, such as a LinkedHashSet
: 您可以使用一个特定的实现,例如
LinkedHashSet
:
Set<Integer> mySet = new LinkedHashSet<>(List.of(new Integer[]{1, 2, 3, 4}));
The Javadoc explicitely states: "The iteration order of set elements is unspecified and is subject to change." Javadoc明确声明:“ set元素的迭代顺序未指定,并且可能会发生变化。”
You could wrap your set in a sorted set like TreeSet
(I also added some generics) 您可以将集合包装在像
TreeSet
这样的排序集合中(我还添加了一些泛型)
SortedSet<Integer> mySet = new TreeSet<>(Set.of(1, 2, 3, 4));
If you need a set that maintains insertion order, you will have to use a LinkedHashSet
instead (note that this is not a sorted set). 如果需要一个保持插入顺序的集合,则必须改用
LinkedHashSet
(请注意,这不是排序的集合)。
Set<Integer> mySet = new LinkedHashSet<>(List.of(1, 2, 3, 4));
You can't using Set.of
. 您不能使用
Set.of
That gives you an immutable Set
instead of one which can be ordered. 这为您提供了一个不变的
Set
而不是可以订购的Set
。
The only way you could do this is if you build a TreeSet
instead (which is ordered if the object if Comparable
, or you can specify your own Comparator
). 唯一的方法是构建
TreeSet
(如果对象为Comparable
, 则可以排序,或者可以指定自己的Comparator
)。
Set<Integer> mySet = new TreeSet<>(Arrays.asList(1, 2, 3, 4));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.