Sub topic 2
What encounter order means
This chapter assumes you know the core java.util types (List, Set, Map, Deque) and the difference between ordered, sorted and unordered collections. It also assumes you can run code on a Java 21 or newer JDK. The sequenced interfaces come in the next chapters. Here we define the idea they are built on.
The definition
A collection has an encounter order if the sequence in which its elements are visited is part of its specification. Iterating with a for loop, an Iterator, forEach, toArray or a stream all visit elements in that order. The order is repeatable. It is not an accident of the current implementation.
Two points are easy to miss:
- Encounter order is about the contract, not about what you happened to observe. A
HashSetof three small integers may print in ascending order on your machine. That does not give it an encounter order, because the specification does not promise it. - Encounter order is not the same as sorted. Sorting is one way to define an order. Insertion sequence and index position are others.
The JDK documentation uses the phrase "defined encounter order" for the collections that promise it. The SequencedCollection interface you will meet next is the type that names this property.
Where the order comes from
Different collections get their order from different sources.
| Collection | Source of order | Defined encounter order? |
|---|---|---|
| `ArrayList`, `LinkedList` | Index position, as maintained by the list | Yes |
| `ArrayDeque` | Head to tail of the deque | Yes |
| `LinkedHashSet`, `LinkedHashMap` | Insertion order, or access order if configured | Yes |
| `TreeSet`, `TreeMap` | The comparator or natural ordering | Yes |
| `HashSet`, `HashMap` | Hash buckets, an implementation detail | No |
| `Set.of`, `Map.of` | Deliberately unspecified | No |
| `PriorityQueue` | Heap layout, partially ordered | No for iteration |
The last row surprises people. A PriorityQueue always hands you the smallest element from poll(), but its iterator walks the internal heap array. The iteration order is not sorted and is not specified, so a PriorityQueue has no defined encounter order.
The immutable Set.of and Map.of factories go further than "unspecified". Their iteration order can differ from one JVM run to the next, by design. This stops programs from depending on an order that was never promised.
Seeing the difference
The following program builds four collections from the same four words. Three of them have a defined order. The fourth does not.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
public class OrderDemo {
public static void main(String[] args) {
List<String> words = List.of("pear", "apple", "fig", "banana");
System.out.println(new ArrayList<>(words)); // [pear, apple, fig, banana]
System.out.println(new LinkedHashSet<>(words)); // [pear, apple, fig, banana]
System.out.println(new TreeSet<>(words)); // [apple, banana, fig, pear]
System.out.println(new HashSet<>(words)); // order is unspecified
}
}The ArrayList and LinkedHashSet reproduce the order in which words was read. The TreeSet follows the natural ordering of String. The HashSet prints whatever its buckets produce. That order may be stable on your machine today. You should still not write a test or a report that depends on it.
Asking the JDK directly
The JDK exposes encounter order through the Spliterator API. A spliterator is the object behind a stream's traversal. It reports a set of characteristics, and ORDERED means "this source has a defined encounter order".
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Spliterator;
import java.util.TreeSet;
public class OrderedCheck {
static boolean hasEncounterOrder(Collection<?> c) {
return c.spliterator().hasCharacteristics(Spliterator.ORDERED);
}
public static void main(String[] args) {
List<Collection<Integer>> samples = List.of(
new ArrayList<>(),
new HashSet<>(),
new LinkedHashSet<>(),
new TreeSet<>());
for (Collection<Integer> c : samples) {
System.out.println(c.getClass().getSimpleName() + ": " + hasEncounterOrder(c));
}
// ArrayList: true
// HashSet: false
// LinkedHashSet: true
// TreeSet: true
}
}This check is useful for exploration. It is not a substitute for a type. A method that takes Collection<?> cannot require an order at compile time, and a runtime flag is easy to forget. The sequenced interfaces exist to move this knowledge into the type system.
Insertion order versus access order
A LinkedHashMap is the one common class where the source of order is configurable. By default it uses insertion order. If you pass true for the accessOrder constructor argument, every get or put of an existing key moves that entry to the end.
import java.util.LinkedHashMap;
public class AccessOrderDemo {
public static void main(String[] args) {
LinkedHashMap<String, Integer> m = new LinkedHashMap<>(16, 0.75f, true);
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
m.get("a"); // touching "a" moves it to the end
System.out.println(m.keySet()); // [b, c, a]
}
}The order is still defined, because the specification states exactly how it changes. The consequence is that even a read operation changes the iteration order. That is why access-ordered maps are the standard base for LRU caches, and why a loop that calls get on the same map while iterating it throws ConcurrentModificationException.
Encounter order and streams
Streams inherit the order of their source. list.stream() is ordered, and new HashSet<>(list).stream() is not. Operations then either respect or ignore that order:
| Operation | Behavior on an ordered stream |
|---|---|
| `findFirst()` | Returns the first element in encounter order |
| `limit(n)`, `skip(n)` | Keep or drop by encounter position |
| `forEach` on a parallel stream | May visit elements in any order |
| `forEachOrdered` | Visits in encounter order, even in parallel |
| `unordered()` | Tells the stream it may ignore the order |
| `sorted()` | Imposes a new order on the stream's output |
The findFirst row is worth remembering. On an unordered source such as a HashSet, findFirst() still returns something, but "first" means nothing stable. If you only need any element, findAny() says so honestly and can be faster in parallel.
What encounter order does not change
Having an encounter order does not turn every operation order-sensitive. Equality is the main example. List.equals compares element by element in order. Set.equals and Map.equals ignore order, even for the linked and tree variants.
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class EqualityDemo {
public static void main(String[] args) {
Set<Integer> a = new LinkedHashSet<>(List.of(1, 2, 3));
Set<Integer> b = new LinkedHashSet<>(List.of(3, 2, 1));
System.out.println(a.equals(b)); // true
System.out.println(new ArrayList<>(a).equals(new ArrayList<>(b))); // false
}
}Two LinkedHashSet instances with opposite iteration orders are equal. Copy them into lists and they are not. Keep this in mind when you compare collections in tests. If order matters to the result, compare as lists. If it does not, comparing as sets is the correct and more tolerant choice.
Common errors
- Depending on
HashMaporHashSetorder. Output may change after a resize, a JDK upgrade or a different insertion history. If a test passes only because of today's hash layout, it is a latent failure. - Treating
PriorityQueueiteration as sorted. Onlypoll()andpeek()honor priority. To print in priority order, drain a copy or sort a copy. - Assuming "sorted" and "ordered" are interchangeable. A
LinkedHashSetis ordered but not sorted. ATreeSetis both. Sortedness adds constraints, such as a position that the comparator decides and you cannot choose, which later chapters cover. - Calling an unordered stream's
findFirstand expecting a stable answer. The call compiles and runs, so nothing warns you. - Forgetting that access order is mutable. In an access-ordered
LinkedHashMap, reads reorder entries. Do not read from such a map inside a loop over the same map. - Copying into a hash-based collection by reflex. Calling
new HashSet<>(list)to remove duplicates discards the order. Usenew LinkedHashSet<>(list)when you need to keep it.
Why this leads to sequenced collections
Before Java 21 the JDK had no single type that meant "this collection has an encounter order". List, Deque, LinkedHashSet and SortedSet all have one, but they share only Collection as a common supertype, and Collection also covers HashSet. Code that wanted "something with a first and last element" had to pick a concrete family and live with its idioms.
The new interfaces fix this by giving the property a name. A collection with a defined encounter order can offer a first element, a last element and a reverse traversal, and the interface says so. The next chapter introduces SequencedCollection and the operations it adds. Everything there relies on the definition in this chapter.
Exercise
A teammate writes Set<String> tags = new HashSet<>(list); to remove duplicates from a list of tags, then prints tags.stream().findFirst().get() and expects the earliest tag from the original list. What is wrong, and what is the smallest fix?
Show answer
A HashSet has no defined encounter order, so "first" is not tied to the original list and may change between runs or JDK versions. The smallest fix is to use new LinkedHashSet<>(list). It removes duplicates and keeps the order in which elements first appeared, so findFirst() returns the earliest tag.
Exercise
You create LinkedHashMap<String, Integer> m = new LinkedHashMap<>(16, 0.75f, true), then call put("x", 1), put("y", 2), put("z", 3), get("x") and get("y"). What does m.keySet() print, and does the map still have a defined encounter order?
Show answer
It prints [z, x, y]. Each get moves its entry to the end, so after get("x") the order is y, z, x, and after get("y") it is z, x, y. The map still has a defined encounter order, because the specification states exactly how access reorders entries. The order is only less stable than insertion order, since reads change it.