Java 21 Simplifies List Access with getLast() Method

Headline: Java 21 finally fixed the most annoying thing about Lists. 🛠️ For over 20 years, if you wanted to get the last element of a List in Java, you had to write this ugly, verbose code: var last = list.get(list.size() - 1); It was prone to "Off-by-One" errors, it was hard to read, and it felt like a workaround. ✅ The Modern Way (Java 21 Sequenced Collections): Java 21 introduced the SequencedCollection interface, which unifies Lists, Deques, and SortedSets. Now, you can just do: var last = list.getLast(); But it gets better. It also standardizes how we reverse collections. ❌ Old Way: Collections.reverse(list); (Modifies the original list in place! 😱) ✅ New Way: list.reversed(); (Returns a lightweight view, keeping the original data safe). Why this matters: It brings consistency to the Collections framework. Whether you are using an ArrayList, a LinkedList, or a LinkedHashSet, the API is finally the same. getFirst() getLast() addFirst() addLast() It’s a small change, but it makes daily coding so much cleaner. Have you started using getLast() yet, or is muscle memory still making you type .get(size() - 1)? #Java #Java21 #SequencedCollections #CleanCode #SoftwareEngineering #CodingTips

💡 Another cool "Modern Java" feature (Java 22): Unnamed Variables. Stop declaring variables you don't use! If you have a catch block where you don't need the exception object, you can now replace it with an underscore _. Before: catch (NumberFormatException ignored) { ... } After: catch (NumberFormatException _) { ... } It clearly signals intent: "I am intentionally ignoring this variable." #Java22 #ModernJava #CleanCode

Like
Reply

To view or add a comment, sign in

Explore content categories