tl;dr
For a consistent encounter order, use an implementation of SequencedSet
: ConcurrentSkipListSet
, LinkedHashSet
, TreeSet
.
new ArrayList < String >
(
new TreeSet < String > // An implementation of `SequencedSet`, `NavigableSet`, and `SortedSet`.
(
List.of( "Bob" , "Carol" , "Alice" , "Alice" )
)
)
.toString()
[Alice, Bob, Carol]
SequencedSet
Java 21 brought sequenced collections. The new interfaces include SequencedSet
.
SequencedSet
is the super-interface of the existing interfaces of NavigableSet
and SortedSet
.
Here is a set of String
objects with natural ordering (alphabetical).
List < String > namesList = List.of( "Bob" , "Carol" , "Alice" , "Alice" );
SequencedSet < String > namesInAlphabeticalOrder = new TreeSet <>( namesList );
namesInAlphabeticalOrder = [Alice, Bob, Carol]
We see two behaviors here:
- Duplicates eliminated, by definition of any
Set
. (One "Alice" instead of two.)
- Natural ordering instilled and maintained in a
SequencedSet
like TreeSet
.
Reliable encounter order
Back to the point of your Question, deriving List
objects from a sequenced set in a reliable order…
A SequenceSet
maintains its order. This means when you iterate, its encounter order will be consistent and reliable. So any List
you derive will be in the same sequence as in the original SequencedSet
.
List< String > listOfNamesInAlphabeticalOrder = new ArrayList< String > ( namesInAlphabeticalOrder ) ;
listOfNamesInAlphabeticalOrder.toString() = [Alice, Bob, Carol]
Set
provides no guarantees as to its iteration order. Not even that it is consistent. It may choose to use your access as an excuse to tidy up the internal structure thereby changing the order on next iteration. – AgnusagoSet
per se. For example, some sets likeTreeSet
andLinkedHashSet
guarantee the iteration order. – SeptuagintSet
- "The elements are returned in no particular order". I.e.Set
specifically states that it provides no guarantees. Talking about specific implantations is completely irrelevant - much like saying that aSet
can be stored in a database becausePersistentSet
happens to be. – AgnusagoSet
. What I meant (pedantically) was that some implementations ofSet
do guarantee iteration order. They are still Sets, i.e. there are Sets that do guarantee iteration order. The distinguishing property of a Set is that it contains no duplicates. All implementations must comply with this constraint. But implementations are free to offer guarantees about iteration order or persistence. – Septuagint