Sequenced Collections

First and Last, Finally (Java 21)

Java 21 added SequencedCollection, SequencedSet and SequencedMap for collections with a defined order (List, Deque, LinkedHashSet, TreeSet, LinkedHashMap, TreeMap). They share getFirst(), getLast(), addFirst(), removeLast() and reversed().

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> recent = new ArrayList<>(List.of("phone", "cover", "charger"));
        System.out.println("first: " + recent.getFirst() + ", last: " + recent.getLast());
        recent.addFirst("earbuds");
        System.out.println("reversed view: " + recent.reversed());

        LinkedHashSet<String> tags = new LinkedHashSet<>(List.of("sale", "new", "trending"));
        System.out.println("last tag: " + tags.getLast());

        SequencedMap<String, Integer> leaderboard = new LinkedHashMap<>();
        leaderboard.put("Asha", 980);
        leaderboard.put("Vikram", 870);
        leaderboard.put("Neha", 790);
        System.out.println("top: " + leaderboard.firstEntry() + ", bottom: " + leaderboard.lastEntry());
        System.out.println("polled: " + leaderboard.pollLastEntry() + " -> " + leaderboard);
    }
}

Output

first: phone, last: charger
reversed view: [charger, cover, phone, earbuds]
last tag: trending
top: Asha=980, bottom: Neha=790
polled: Neha=790 -> {Asha=980, Vikram=870}