Lesson 287 of 296
Java collections, generics and streams
What you will learn
- The collections framework: List, Set, Map, Queue
- Generics
- Boxing and the Integer == trap
- Iterating and removing safely
- Lambdas and streams
- Optional
On this page
The collections framework
Java separates interfaces (what it does) from implementations (how):
| Interface | Main implementations | Like in TypeScript |
|---|---|---|
| List | ArrayList, LinkedList | Array |
| Set | HashSet, LinkedHashSet, TreeSet | Set |
| Map | HashMap, LinkedHashMap, TreeMap | Map |
| Queue / Deque | ArrayDeque, PriorityQueue | Array used as a queue or stack |
Declare variables with the interface type, so you can change the implementation later: List<String> names = new ArrayList<>();.
import java.util.*;
public class Collections1 {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("sam", "ana"));
names.add("leo");
names.sort(null); // natural order
System.out.println(names + " " + names.get(0) + " " + names.size()); // [ana, leo, sam] ana 3
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 10);
stock.merge("pen", 5, Integer::sum); // add 5 to the existing value
System.out.println(stock.get("pen") + " " + stock.getOrDefault("cup", 0)); // 15 0
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}
Set<Integer> seen = new HashSet<>(List.of(1, 2, 2, 3));
System.out.println(seen.size() + " " + seen.contains(2)); // 3 true
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
System.out.println(stack.pop()); // 2 (stack: last in, first out)
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1); queue.offer(2);
System.out.println(queue.poll()); // 1 (queue: first in, first out)
PriorityQueue<Integer> heap = new PriorityQueue<>(List.of(5, 1, 4));
System.out.println(heap.poll()); // 1 (min-heap by default)
}
}| Implementation | Order | Main costs |
|---|---|---|
| ArrayList | Insertion order | get O(1), add at end O(1), insert/remove in middle O(n) |
| HashMap / HashSet | No guaranteed order | get / put / contains O(1) average |
| LinkedHashMap | Insertion order | Same as HashMap |
| TreeMap / TreeSet | Sorted | O(log n) |
| ArrayDeque | Both ends | push/pop/offer/poll O(1) |
| PriorityQueue | Smallest first | offer/poll O(log n), peek O(1) |
List.of(...) and Map.of(...) create immutable collections: add throws UnsupportedOperationException.
Generics
Generics let classes and methods work with any type while staying type-safe, like Array<T> in TypeScript.
import java.util.List;
public class Generics {
static <T extends Comparable<T>> T maxOf(List<T> items) { // bounded type parameter
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
public static void main(String[] args) {
Box<String> b = new Box<>("hello");
System.out.println(b.get().length()); // 5, no cast needed
System.out.println(maxOf(List.of(3, 9, 4))); // 9
System.out.println(maxOf(List.of("pear", "apple"))); // pear
}
}
class Box<T> {
private final T value;
Box(T value) { this.value = value; }
T get() { return value; }
}Generics only work with reference types: you write List<Integer>, not List<int>. Java removes generic types after compiling (type erasure), so you cannot check list instanceof List<String> at runtime.
Boxing and the Integer == trap
Java automatically converts between int and Integer (autoboxing and unboxing). This creates a famous trap:
public class Boxing {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true (small values are cached)
System.out.println(c == d); // false (different objects!)
System.out.println(c.equals(d)); // true (compare values)
Integer missing = null;
try {
int x = missing; // unboxing null
System.out.println(x);
} catch (NullPointerException e) {
System.out.println("NullPointerException when unboxing null");
}
}
}Rule: compare objects, including Integer and String, with .equals().
Iterating and removing safely
Removing from a list while looping over it with a for-each loop throws ConcurrentModificationException. Use removeIf or an iterator.
import java.util.ArrayList;
import java.util.List;
public class RemoveSafely {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
nums.removeIf(n -> n % 2 == 0);
System.out.println(nums); // [1, 3, 5]
}
}Lambdas and streams
A lambda is a short function: n -> n * 2. Streams process collections step by step, like map, filter and reduce on arrays in TypeScript.
import java.util.*;
import java.util.stream.*;
public class StreamsDemo {
record Order(String customer, double total) {}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("sam", 40), new Order("ana", 120), new Order("sam", 60));
List<String> bigCustomers = orders.stream()
.filter(o -> o.total() > 50)
.map(Order::customer) // method reference
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println(bigCustomers); // [ana, sam]
double sum = orders.stream().mapToDouble(Order::total).sum();
System.out.println(sum); // 220.0
Map<String, Double> byCustomer = orders.stream()
.collect(Collectors.groupingBy(Order::customer, TreeMap::new,
Collectors.summingDouble(Order::total)));
System.out.println(byCustomer); // {ana=120.0, sam=100.0}
Comparator<Order> byTotalDesc = Comparator.comparingDouble(Order::total).reversed();
System.out.println(orders.stream().sorted(byTotalDesc).findFirst().get().customer()); // ana
}
}Streams are lazy: nothing runs until a final step such as collect, sum or findFirst. A stream can be used only once.
Optional
Optional<T> is a box that may or may not contain a value. It makes "might be missing" explicit in a method's return type, instead of returning null.
import java.util.*;
public class OptionalDemo {
static Optional<String> findEmail(Map<String, String> emails, String user) {
return Optional.ofNullable(emails.get(user));
}
public static void main(String[] args) {
Map<String, String> emails = Map.of("sam", "sam@example.com");
System.out.println(findEmail(emails, "sam").orElse("none")); // sam@example.com
System.out.println(findEmail(emails, "zoe").orElse("none")); // none
System.out.println(findEmail(emails, "sam").map(String::length).orElse(0)); // 15
}
}Use Optional for return values, not for fields or parameters. Avoid calling .get() without checking; use orElse, orElseThrow, map or ifPresent.
How to say it in an interview
"I declare collections by interface, like List or Map, and pick the implementation for the job: ArrayList for most lists, HashMap and HashSet for O(1) lookups, TreeMap when I need sorted keys, ArrayDeque for stacks and queues and PriorityQueue for heaps. Generics give type safety with reference types only, because of type erasure. I always compare Integer and String with equals because == compares references, and only small Integers are cached. I use streams with lambdas for filtering, mapping and grouping, removeIf to delete while iterating, and Optional for return values that may be missing."
Key words
| Word | Meaning |
|---|---|
| Collections framework | Java's standard interfaces and classes for lists, sets, maps and queues |
| Generics | Type parameters such as List<String> |
| Type erasure | Generic types are removed after compiling |
| Autoboxing | Automatic conversion between int and Integer |
| Lambda | A short anonymous function |
| Stream | A lazy pipeline of operations on a collection |
| Optional | A container that may hold a value or be empty |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.