Menu

How to choose Java collection types: List, Set, Map
📰

How to choose Java collection types: List, Set, Map

DEV Community: java·duong vu·9 days ago
#Oboa6EF3
#devtojava#devto#dev#list#java
Long article (2942 words) — no AI summary yet.
Reading 0:00
15s threshold

Originally published at Shipped Code .

Most backend Java code gets by with ArrayList and HashMap , until a method returns a list nobody can add to or a loop throws ConcurrentModificationException . How you choose a Java collection comes down to 3 questions. Do you need duplicates and positions? Use a List ( ArrayList by default). Do you need uniqueness? Use a Set ( HashSet , or LinkedHashSet to keep insertion order, TreeSet to keep it sorted). Do you look things up by key? Use a Map ( HashMap , or LinkedHashMap / TreeMap when order matters).

Return List.copyOf(...) from methods so callers cannot change your data, keep LinkedList for the rare case you have measured, and switch to ConcurrentHashMap once several threads write to the same map. The classic trap is removing elements inside a for-each loop, and removeIf fixes it.

This post is for developers who write Java every day.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.