← Java roadmap

Topic 12 of 30 · Advanced

Functions Reference: Collections & Stream API

List, Set and Map methods, Collections utilities and Stream pipelines with complexity notes.

Concept

The Collections Framework gives interfaces (List, Set, Map) and implementations (ArrayList, HashSet, HashMap, TreeMap…). You call the same interface methods whichever implementation you pick — only performance changes.

ArrayList get(i) is O(1) but contains/remove(Object) are O(n). HashSet/HashMap add, contains, get and remove are O(1) on average. TreeMap/TreeSet keep keys sorted at O(log n).

Streams (Java 8+) describe a pipeline: a source (.stream()), lazy intermediate operations (filter, map, sorted…) and one terminal operation (collect, reduce, count…) that actually runs it. A stream can be used only once.

Cheat sheet

MethodWhat it doesExample → result
list.add(x) / add(i, x)Append / insertlist.add(5)
list.remove(i) / remove(Object)Remove by index / by valuelist.remove(Integer.valueOf(5))
list.get(i) / set(i, x)Read / replace at indexlist.get(0)
c.contains(x)Membership testset.contains("a") → true
c.isEmpty() / size()Empty check / countlist.size() → 3
map.put(k, v)Add or overwritemap.put("a", 1)
map.get(k)Value or nullmap.get("z") → null
map.getOrDefault(k, d)Value or defaultmap.getOrDefault("z", 0) → 0
map.containsKey(k) / containsValue(v)Key test O(1) / value test O(n)map.containsKey("a") → true
map.keySet() / values() / entrySet()Views to iteratefor (var e : map.entrySet())
map.computeIfAbsent(k, fn)Create value only when missinggraph.computeIfAbsent(u, k -> new ArrayList<>()).add(v)
map.merge(k, 1, Integer::sum)Increment a counterword frequency
Collections.sort(list[, cmp])Stable sortCollections.sort(names)
Collections.frequency(c, x)Count occurrencesfrequency(List.of(1,1,2), 1) → 2
Collections.reverse(list)Reverse in place[1,2,3] → [3,2,1]
.stream()Start a pipelinelist.stream()
.filter(pred)Keep matching items.filter(n -> n % 2 == 0)
.map(fn)Transform each item.map(String::toUpperCase)
.flatMap(fn)Flatten nested streams.flatMap(List::stream)
.distinct()Remove duplicates (equals/hashCode)[1,1,2] → [1,2]
.sorted([cmp])Sort.sorted(Comparator.reverseOrder())
.peek(action)Look at items (debugging).peek(System.out::println)
.limit(n) / .skip(n)First n / drop n.skip(1).limit(2)
.collect(Collectors.toList())Gather into a list (or .toList() in Java 16+)→ [2, 4]
Collectors.groupingBy / counting / joiningGroup, count, join stringsgroupingBy(s -> s.charAt(0))
.reduce(identity, op)Fold to one value.reduce(0, Integer::sum)
.count()Number of items→ 3
.anyMatch / allMatch / noneMatchShort-circuit tests.anyMatch(n -> n > 10)

Code (Java 21)

import java.util.*;
import java.util.stream.*;

public class StreamsDemo {
    public static void main(String[] args) {
        List<String> words = List.of("java", "spark", "sql", "java", "stream");

        // Frequency map, two ways
        Map<String, Integer> freq = new HashMap<>();
        for (String w : words) freq.put(w, freq.getOrDefault(w, 0) + 1);
        System.out.println(freq.get("java"));                         // 2
        System.out.println(Collections.frequency(words, "java"));      // 2

        // Adjacency list
        Map<Integer, List<Integer>> graph = new HashMap<>();
        int[][] edges = {{1, 2}, {1, 3}, {2, 3}};
        for (int[] e : edges) graph.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]);
        System.out.println(graph);                                     // {1=[2, 3], 2=[3]}

        // Stream pipeline
        List<String> result = words.stream()
            .distinct()
            .filter(w -> w.length() > 3)
            .map(String::toUpperCase)
            .sorted()
            .collect(Collectors.toList());
        System.out.println(result);                                    // [JAVA, SPARK, STREAM]

        int totalLength = words.stream().map(String::length).reduce(0, Integer::sum);
        long longOnes = words.stream().filter(w -> w.length() >= 5).count();
        boolean hasSql = words.stream().anyMatch("sql"::equals);
        System.out.println(totalLength + " " + longOnes + " " + hasSql); // 22 2 true

        List<Integer> flat = Stream.of(List.of(1, 2), List.of(3))
            .flatMap(List::stream).skip(1).limit(2).toList();
        System.out.println(flat);                                      // [2, 3]
    }
}

Remember

  • list.remove(1) removes index 1; use Integer.valueOf(1) to remove the value.
  • Streams are lazy — nothing runs until a terminal operation.
  • A stream can be consumed only once.
  • List.of(...) and .toList() return unmodifiable lists.

Interview questions

map vs flatMap?

map turns each item into exactly one item; flatMap turns each item into a stream and flattens them all into one stream.

HashMap vs TreeMap?

HashMap has O(1) average operations and no order; TreeMap keeps keys sorted with O(log n) operations.

What happens if you modify a list while iterating with for-each?

ConcurrentModificationException. Use an Iterator's remove(), removeIf, or collect into a new list.

Intermediate vs terminal operations?

Intermediate ones (filter, map, sorted) return a new lazy stream; terminal ones (collect, count, reduce, forEach) produce a result and trigger execution.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Functions Reference: Collections & Stream API” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.