Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
A tour of the Java collection interfaces: Collection versus Map, List with random access and the remove(int) trap, Set equality, SortedSet and NavigableSet, the Java 21 SequencedCollection, SequencedSet and SequencedMap, RandomAccess, and an overview of all concrete collection classes.
kvi5hnuCode Sprout team member9 min readOn this page
The Java Collections Framework defines a family of interfaces for different kinds of collections, and a set of concrete classes that implement them. Knowing the interfaces tells you what operations you can rely on. Knowing the classes tells you what performance to expect. This article maps out both, including the sequenced collection interfaces that Java 21 added. The interfaces for concurrent programming come later, in the concurrency part of the course.

Two roots: Collection and Map
There are two fundamental interfaces, Collection and Map. You insert elements into a collection with
boolean add(E element)
Maps hold key/value pairs, and you insert them with put:
V put(K key, V value)
To read elements from a collection, you visit them with an iterator. To read a value from a map, you look it up by key with get:
V get(Object key)
List: ordered, with positions
A List is an ordered collection. Elements go into specific positions, and you can access them in two ways: with an iterator, or by integer index. Index access is called random access, because elements can be visited in any order. An iterator must visit them sequentially.
List defines these random-access methods:
void add(int index, E element)
E remove(int index)
E get(int index)
E set(int index, E element)
set and remove return the element that was replaced or removed. The ListIterator subinterface of Iterator adds a method for inserting an element before the iterator position. It's covered in the next article.
The List documentation also defines equals precisely. A list is equal to another object only if the other object is also a list, both have the same size, and corresponding elements are equal. So an ArrayList and a LinkedList with the same elements in the same order are equal.
A design wart: two kinds of lists, one interface
There's a problem with the List interface. There are really two kinds of ordered collections with very different performance:
- A list backed by an array has fast random access, so index methods make sense.
- A linked list is also ordered, but random access is slow. It is best traversed sequentially with an iterator.
It would have been better to have two interfaces. To soften the problem, Java 1.4 introduced the marker interface RandomAccess. It has no methods, but you can use it to test whether a list supports efficient random access:
if (c instanceof RandomAccess) {
use random access algorithm
} else {
use sequential access algorithm
}
ArrayList implements RandomAccess. LinkedList doesn't. Library algorithms such as Collections.binarySearch use this test to choose their strategy.
Set: no duplicates
The Set interface has the same methods as Collection, but their behavior is defined more tightly:
addmust reject duplicates.equalsmust returntruefor two sets with the same elements, not necessarily in the same order.hashCodemust return the same value for two sets with the same elements.
Why have a separate interface if the method signatures are identical? Conceptually, not every collection is a set. A Set interface lets you write methods that accept only sets. Equality shows why that matters: two lists are equal if they have the same elements in the same order, while two sets are equal if they have the same elements in any order. A set's equals must therefore check that the other object is a Set, not just any Collection. A list never equals a set, even with the same elements.
Sorted and navigable sets and maps
SortedSet and SortedMap expose the comparator used for sorting and define methods that return views of parts of the collection, such as all elements below a given one. The article on views and sublists covers them.
NavigableSet and NavigableMap add methods for finding the next or previous element relative to a given value: ceiling, floor, higher, lower, plus pollFirst and pollLast and descending views. TreeSet and TreeMap implement these interfaces, because tree-based data structures support the navigation operations efficiently.
Sequenced collections (Java 21)
Before Java 21, getting the first or last element of a collection was strangely inconsistent:
| Collection | First element | Last element |
|---|---|---|
List | list.get(0) | list.get(list.size() - 1) |
Deque | deque.getFirst() | deque.getLast() |
SortedSet | set.first() | set.last() |
LinkedHashSet | set.iterator().next() | no direct way |
Java 21 (JEP 431) introduced the interface SequencedCollection<E> for every collection with a defined encounter order. It provides uniform access to both ends and a reverse view:
E getFirst()
E getLast()
void addFirst(E e)
void addLast(E e)
E removeFirst()
E removeLast()
SequencedCollection<E> reversed()
List and Deque extend SequencedCollection. The subinterface SequencedSet sharpens the return type of reversed to SequencedSet. LinkedHashSet implements it, and SortedSet extends it. For maps, SequencedMap has analogous methods: firstEntry, lastEntry, pollFirstEntry, pollLastEntry, putFirst, putLast, reversed, and the views sequencedKeySet, sequencedValues and sequencedEntrySet. LinkedHashMap and SortedMap (and therefore TreeMap) implement it.
reversed() returns a view, not a copy: changes to the original show through, and vice versa where modification is supported. Collections whose order is determined by sorting, such as TreeSet, throw UnsupportedOperationException from addFirst and addLast, because you can't choose where an element goes.
The concrete collections
This table lists the general-purpose collection classes. The thread-safe collections come later, in the concurrency part. All classes whose names end in Map implement Map. All others implement Collection.
| Class | Description | Article |
|---|---|---|
ArrayList | An indexed sequence that grows and shrinks dynamically | LinkedList vs ArrayList |
LinkedList | An ordered sequence with efficient insertion and removal at any position | LinkedList vs ArrayList |
ArrayDeque | A double-ended queue implemented as a circular array | Queues and deques |
HashSet | An unordered collection that rejects duplicates | HashSet and TreeSet |
TreeSet | A sorted set | HashSet and TreeSet |
EnumSet | A set of values of an enumerated type | Map views and special maps |
LinkedHashSet | A set that remembers insertion order | Map views and special maps |
PriorityQueue | A collection that allows efficient removal of the smallest element | Queues and deques |
HashMap | A data structure that stores key/value associations | Maps |
TreeMap | A map whose keys are sorted | Maps |
EnumMap | A map whose keys belong to an enumerated type | Map views and special maps |
LinkedHashMap | A map that remembers the order in which entries were added | Map views and special maps |
WeakHashMap | A map whose values can be reclaimed by the garbage collector when the keys aren't used elsewhere | Map views and special maps |
IdentityHashMap | A map whose keys are compared with ==, not equals | Map views and special maps |
The demo prints which interfaces each class implements, a compact picture of how the classes relate.
A complete example
import java.time.DayOfWeek;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. collections add elements; maps put key/value pairs and get by key
Collection<String> names = new ArrayList<>();
names.add("Ada");
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
System.out.println("collection " + names + ", map get: " + ages.get("Ada"));
// 2. List: positional access
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.add(1, "x"); // insert at index 1
String old = list.set(0, "A"); // replace, returns the old element
String removed = list.remove(2); // remove by index
System.out.println(list + " get(1)=" + list.get(1) + " replaced " + old + " removed " + removed);
// the remove(int) / remove(Object) trap with List<Integer>
List<Integer> ids = new ArrayList<>(List.of(10, 20, 0, 30));
int id = 0;
ids.remove(id); // removes INDEX 0 (the 10), not the value 0
System.out.println("after remove(int 0): " + ids);
ids.remove(Integer.valueOf(0)); // removes the VALUE 0
System.out.println("after remove(Integer 0): " + ids);
// list equality: same elements, same order, any List implementation
System.out.println("ArrayList equals LinkedList: " + List.of(1, 2).equals(new LinkedList<>(List.of(1, 2))));
System.out.println("order matters: " + List.of(1, 2).equals(List.of(2, 1)));
System.out.println("RandomAccess: ArrayList " + (new ArrayList<>() instanceof RandomAccess)
+ ", LinkedList " + (new LinkedList<>() instanceof RandomAccess));
// 3. Set: no duplicates, equality ignores order
Set<String> s1 = new HashSet<>(List.of("x", "y", "z"));
Set<String> s2 = new TreeSet<>(List.of("z", "y", "x", "x"));
System.out.println("sets equal: " + s1.equals(s2) + ", sizes " + s1.size() + " " + s2.size()
+ ", same hashCode: " + (s1.hashCode() == s2.hashCode()));
System.out.println("a list never equals a set: " + List.of("x").equals(Set.of("x")));
// 4. SortedSet / NavigableSet
NavigableSet<Integer> scores = new TreeSet<>(List.of(70, 85, 92, 60));
System.out.println("first " + scores.first() + ", last " + scores.last()
+ ", ceiling(80) " + scores.ceiling(80) + ", headSet(85) " + scores.headSet(85));
// 5. Java 21 sequenced collections: one API for first/last/reversed
List<String> seqList = new ArrayList<>(List.of("b", "c"));
seqList.addFirst("a");
seqList.addLast("d");
System.out.println("list: first " + seqList.getFirst() + ", last " + seqList.getLast() + ", reversed " + seqList.reversed());
Deque<String> deque = new ArrayDeque<>(List.of("p", "q", "r"));
System.out.println("deque: removeFirst " + deque.removeFirst() + ", reversed " + deque.reversed());
SequencedSet<String> linked = new LinkedHashSet<>(List.of("one", "two", "three"));
System.out.println("LinkedHashSet: getLast " + linked.getLast() + ", reversed " + linked.reversed());
SequencedMap<String, Integer> sm = new LinkedHashMap<>();
sm.put("first", 1);
sm.put("second", 2);
sm.putFirst("zeroth", 0);
System.out.println("map: firstEntry " + sm.firstEntry() + ", lastEntry " + sm.lastEntry()
+ ", reversed " + sm.reversed());
// 6. which interfaces does each concrete class implement?
Object[] samples = { new ArrayList<>(), new LinkedList<>(), new ArrayDeque<>(), new HashSet<>(),
new LinkedHashSet<>(), new TreeSet<>(), EnumSet.noneOf(DayOfWeek.class), new PriorityQueue<>(),
new HashMap<>(), new LinkedHashMap<>(), new TreeMap<>(), new EnumMap<>(DayOfWeek.class) };
System.out.printf("%-14s %-5s %-4s %-6s %-6s %-10s %-6s %-4s %s%n",
"class", "List", "Set", "Queue", "Deque", "Sequenced", "Sorted", "Map", "SequencedMap");
for (Object o : samples)
System.out.printf("%-14s %-5s %-4s %-6s %-6s %-10s %-6s %-4s %s%n",
o instanceof EnumSet ? "EnumSet" : o.getClass().getSimpleName(),
mark(o instanceof List), mark(o instanceof Set), mark(o instanceof Queue), mark(o instanceof Deque),
mark(o instanceof SequencedCollection), mark(o instanceof SortedSet || o instanceof SortedMap),
mark(o instanceof Map), mark(o instanceof SequencedMap));
}
static String mark(boolean b) { return b ? "yes" : "-"; }
}
collection [Ada], map get: 36
[A, x, c] get(1)=x replaced a removed b
after remove(int 0): [20, 0, 30]
after remove(Integer 0): [20, 30]
ArrayList equals LinkedList: true
order matters: false
RandomAccess: ArrayList true, LinkedList false
sets equal: true, sizes 3 3, same hashCode: true
a list never equals a set: false
first 60, last 92, ceiling(80) 85, headSet(85) [60, 70]
list: first a, last d, reversed [d, c, b, a]
deque: removeFirst p, reversed [r, q]
LinkedHashSet: getLast three, reversed [three, two, one]
map: firstEntry zeroth=0, lastEntry second=2, reversed {second=2, first=1, zeroth=0}
class List Set Queue Deque Sequenced Sorted Map SequencedMap
ArrayList yes - - - yes - - -
LinkedList yes - yes yes yes - - -
ArrayDeque - - yes yes yes - - -
HashSet - yes - - - - - -
LinkedHashSet - yes - - yes - - -
TreeSet - yes - - yes yes - -
EnumSet - yes - - - - - -
PriorityQueue - - yes - - - - -
HashMap - - - - - - yes -
LinkedHashMap - - - - - - yes yes
TreeMap - - - - - yes yes yes
EnumMap - - - - - - yes -
Notice that HashSet and PriorityQueue don't implement SequencedCollection. Their iteration order isn't meaningful, so "first" and "last" would be meaningless too.
Common questions
What is the difference between a List and a Set?
A list keeps elements in positions and allows duplicates. Two lists are equal if they have the same elements in the same order. A set has no duplicates, and two sets are equal if they contain the same elements in any order.
Which collections have a getFirst method?
Since Java 21, every SequencedCollection: all lists, all deques, LinkedHashSet and sorted sets such as TreeSet. Maps with an order, such as LinkedHashMap and TreeMap, have firstEntry. HashSet and HashMap don't, because their order isn't defined.
Is list.reversed() expensive?
No. It returns a view of the same list in reverse order without copying anything. If you want an independent reversed copy, write new ArrayList<>(list.reversed()).
Why does list.remove(1) remove the wrong element from my List<Integer>?
The int argument selects remove(int index), so it removes the element at index 1, not the value 1. Call list.remove(Integer.valueOf(1)) to remove by value.
When should I use EnumSet and EnumMap?
Whenever the elements or keys are constants of one enum. They're stored as bit vectors or arrays indexed by ordinal, so they're much faster and smaller than HashSet and HashMap, and they iterate in declaration order.
Summary
Collection(elements,add, iteration) andMap(key/value pairs,put,get) are the two roots of the framework.Listis ordered, with index operationsadd(int, E),get,set,remove(int). Bewareremove(int)versusremove(Object)onList<Integer>.RandomAccessmarks lists with fast index access, such asArrayListbut notLinkedList.Setrejects duplicates. Two sets are equal if they have the same elements, regardless of order.SortedSet/SortedMapexpose the comparator and subrange views.NavigableSet/NavigableMapadd nearest-match navigation.- Java 21's
SequencedCollection,SequencedSetandSequencedMapgive every ordered collectiongetFirst,getLast,addFirst,addLast,removeFirst,removeLastand areversed()view. - Prefer
ArrayList,ArrayDeque,HashSetandHashMapby default. Choose linked or tree variants when you need ordering.
Practice Questions
ids is a List<Integer> containing [5, 0, 7]. What do ids.remove(0) and ids.remove(Integer.valueOf(0)) do?
ids.remove(0) removes the element at index 0, the 5, leaving [0, 7]. ids.remove(Integer.valueOf(0)) removes the value 0, leaving [5, 7] when applied to the original list.
Is new ArrayList<>(List.of(1, 2)).equals(new LinkedList<>(List.of(1, 2))) true?
Yes. List equality depends only on the elements and their order, not on the implementation class.
Why does Set exist if it declares the same methods as Collection?
Its methods have stricter contracts: no duplicates, and order-independent equals and hashCode. A separate type also lets methods require a set specifically.
How do you get the last element of a LinkedHashSet in Java 21? And before Java 21?
Java 21: set.getLast(). Before that, you had to iterate through the whole set, or copy it into a list, because LinkedHashSet had no method for its last element.
Why does TreeSet.addFirst throw UnsupportedOperationException?
A TreeSet places elements according to their sort order. The caller can't choose a position, so the positional addFirst and addLast methods can't be supported.
What is RandomAccess, and how would an algorithm use it?
A marker interface with no methods, implemented by lists with fast index access. An algorithm can check list instanceof RandomAccess and use get(i) loops if so, or iterator-based traversal otherwise.
Previous: The Java Collections Framework: Interfaces, Implementations and Iterators
Next: Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
Related reading
- The Java Collections Framework: Interfaces, Implementations and Iterators
- Java ArrayList: Generic Array Lists Explained
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.