How to keep order in Java 9 Set.of

Viewed 842

I've noted while testing that the new Set.of method of Java 9 doesn't return an ordered implementation of a 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.

3 Answers

The immutable Sets created by Set.of make no guarantee about the iteration order of their elements. You could use a specific implementation that does, such as a 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."

You could wrap your set in a sorted set like TreeSet (I also added some generics)

 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).

  Set<Integer> mySet = new LinkedHashSet<>(List.of(1, 2, 3, 4));

You can't using Set.of. That gives you an immutable Set instead of one which can be ordered.

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).

Set<Integer> mySet = new TreeSet<>(Arrays.asList(1, 2, 3, 4));
Related