Last 30 Days
No notifications
The Java Collections Framework gives you ready-made data structures: List (ordered, duplicates), Set (unique), Map (keyβvalue). You always code to the *interface* and pick the *implementation* based on performance trade-offs (ArrayList vs LinkedList, HashMap vs TreeMap, β¦).
# Collections Framework
Collection
βββ List ordered, duplicates allowed β ArrayList, LinkedList
βββ Set unique elements β HashSet, LinkedHashSet, TreeSet
βββ Queue FIFO / priority β ArrayDeque, PriorityQueueMap (NOT a Collection) key β value β HashMap, LinkedHashMap, TreeMap
List<String> names = new ArrayList<>(); // good
Map<String,Integer> ages = new HashMap<>();
The diamond <> lets the compiler infer the type arguments (Java 7+).| op | ArrayList | LinkedList |
| get(i) | O(1) | O(n) |
| add at end | amortised O(1) | O(1) |
| insert middle | O(n) | O(1) (with iterator) |
| memory | low | high (node per element) |
Use ArrayList by default. LinkedList is rarely the right answer.
HashSet β unordered, O(1) add/containsLinkedHashSet β *insertion* order preservedTreeSet β sorted (natural or by Comparator), O(log n)for (String s : names) System.out.println(s);for (var e : ages.entrySet())
System.out.println(e.getKey() + " = " + e.getValue());
names.forEach(System.out::println); // Java 8+
List<Integer> a = List.of(1, 2, 3);
Set<String> b = Set.of("x", "y");
Map<String,Integer> c = Map.of("a", 1, "b", 2);
These throw UnsupportedOperationException on add/put.Collections.sort(list); // natural order, in place
Collections.sort(list, Comparator.reverseOrder());
Collections.reverse(list);
Collections.shuffle(list);
int min = Collections.min(list);
int max = Collections.max(list);// frequency count
Map<String,Integer> freq = new HashMap<>();
for (String w : words) freq.merge(w, 1, Integer::sum);// default if missing
int v = freq.getOrDefault("xyz", 0);
// compute if absent
Map<String,List<Integer>> groups = new HashMap<>();
groups.computeIfAbsent("evens", k -> new ArrayList<>()).add(2);