javaset

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.

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.


Solution

  • 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}));