iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Collections Framework

Java’s Collections Framework gives you typed containers: List, Set, Queue, Map. Multiple implementations per interface; pick by performance characteristics, not name.

List, Set, Map, Queue, immutable factories

EXAMPLE
import java.util.*;
import java.util.concurrent.*;
import static java.util.stream.Collectors.toMap;

// 1) List — ordered, allows duplicates
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Bo");
names.add("Cy");

for (String n : names) System.out.println(n);
names.forEach(System.out::println);
String first = names.get(0);
names.remove("Bo");
names.sort(Comparator.naturalOrder());

// LinkedList — when you frequently add/remove from the front/middle
List<Integer> queue = new LinkedList<>();
((LinkedList<Integer>) queue).addFirst(0);

// CopyOnWriteArrayList — concurrent reads, rare writes
List<String> safe = new CopyOnWriteArrayList<>();

// 2) Set — unique elements
Set<String> tags = new HashSet<>(List.of("vip", "beta", "vip"));
// → 2 elements; insertion order NOT preserved

Set<String> ordered = new LinkedHashSet<>(List.of("a", "b", "c"));
// → preserves insertion order

Set<Integer> sorted = new TreeSet<>(List.of(3, 1, 2));
// → sorted: [1, 2, 3]; lookup O(log n)

// 3) Map — key/value
Map<String, Integer> scores = new HashMap<>();
scores.put("Ada", 95);
scores.put("Bo",  88);
int v = scores.get("Bo");
int d = scores.getOrDefault("Cy", 0);
scores.putIfAbsent("Cy", 70);
scores.merge("Ada", 5, Integer::sum);          // increment by 5
scores.computeIfAbsent("Di", k -> 100);

// LinkedHashMap — predictable iteration order
// TreeMap        — sorted by key, range queries
// ConcurrentHashMap — concurrent reads + writes

for (Map.Entry<String, Integer> e : scores.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}
scores.forEach((k, v2) -> System.out.println(k + "=" + v2));

// 4) Queue / Deque
Deque<String> stack = new ArrayDeque<>();    // preferred over Stack class
stack.push("a");
stack.push("b");
stack.pop();                                  // "b"

Queue<Integer> q = new ArrayDeque<>();
q.offer(1); q.offer(2);
q.poll();                                     // 1

PriorityQueue<Task> pq = new PriorityQueue<>(
    Comparator.comparingInt(Task::priority).reversed()
);

// 5) Concurrent
Map<String, Long> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent("a", k -> 0L);
counts.compute("a", (k, n) -> n + 1);

BlockingQueue<Job> work = new LinkedBlockingQueue<>();
work.put(job);                                 // blocks if full (bounded variant)
Job j = work.take();                            // blocks until available

// 6) Immutable factories (Java 9+)
List<String>     L = List.of("a", "b", "c");
Set<String>      S = Set.of("a", "b");
Map<String, Integer> M = Map.of("a", 1, "b", 2);
Map<String, Integer> M2 = Map.ofEntries(
    Map.entry("a", 1),
    Map.entry("b", 2),
);
// These throw UnsupportedOperationException on modification.

// 7) Convert with Streams
import java.util.stream.*;
Map<String, Long> tagCount = posts.stream()
    .flatMap(p -> p.tags().stream())
    .collect(toMap(t -> t, t -> 1L, Long::sum));

List<String> uniqueSorted = names.stream()
    .distinct()
    .sorted()
    .toList();   // Java 16+ — immutable list

// 8) Choosing the right collection
//   - ArrayList         : default List
//   - LinkedList        : frequent add/remove at ends
//   - HashMap / HashSet : default
//   - LinkedHashMap     : iteration order = insertion order
//   - TreeMap / TreeSet : sorted + range queries
//   - ConcurrentHashMap : concurrent access
//   - CopyOnWriteArrayList : many readers, rare writers (event listeners)
//   - ArrayDeque         : default Stack + Queue replacement

Why it matters

computeIfAbsent, computeIfPresent, merge, getOrDefault remove the most common “check then put” boilerplate. Read the Map interface once — you’ll delete a lot of code.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import java.util.*;
List<String> xs = new ArrayList<>(List.of("a","b"));
xs.add("c");
Map<String, Integer> m = new HashMap<>();
m.put("ada", 36);
Try it Yourself »

Exercise

Create an empty ArrayList of String.

List<String> xs = new <>();

Test yourself

Q1. Most-used List implementation is…
Q2. Most-used Map implementation is…
Q3. List.of(...) returns a list that is…

Discussion

Loading…