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.…