Skip to lesson

map vs flatMap, groupingBy and Collectors

"Write this with streams" questions almost always end in a collector, and stream theory questions often start with map vs flatMap. The interviewer checks that you pick the right one and know the trap that goes with it.

map vs flatMap

map / flatMap are the two ways to transform a stream. map turns each element into exactly one new element; flatMap turns each element into a stream of zero or more elements and joins them all into one flat stream.

An order holds a list of items. map keeps each list as one element, while flatMap opens the lists and gives one flat stream of items.

flatMap flattens lists. Asha has Maths, Physics; Ravi has Maths, Chemistry, Biology; Meena has none; Kiran has English, Maths. flatMap(s -> s.subjects().stream()) joins them into one stream of 7 subjects, three of them Maths.

Example 1 · map vs flatMap on a list of lists

MapVsFlatMapDemo.javaJava
import java.util.List;import java.util.stream.Stream;
public class MapVsFlatMapDemo {    public static void main(String[] args) {        List<List<String>> blocks = List.of(                List.of("A-101", "A-102"),                List.of("B-201"),                List.of("C-301", "C-302", "C-303"));
        List<Integer> sizes = blocks.stream().map(List::size).toList();        System.out.println("map(List::size):        " + sizes);
        List<Stream<String>> nested = blocks.stream().map(List::stream).toList();        System.out.println("map(List::stream) gives " + nested.size() + " separate streams");
        List<String> rooms = blocks.stream().flatMap(List::stream).toList();        System.out.println("flatMap(List::stream):  " + rooms);
        List<String> letters = Stream.of("UPI", "PAY")                .flatMap(w -> w.chars().mapToObj(c -> String.valueOf((char) c)))                .distinct()                .toList();        System.out.println("Distinct letters:       " + letters);    }}
Output
map(List::size):        [2, 1, 3]
map(List::stream) gives 3 separate streams
flatMap(List::stream):  [A-101, A-102, B-201, C-301, C-302, C-303]
Distinct letters:       [U, P, I, A, Y]

What this code does

  • map(List::size) turns each hostel block into one number. map(List::stream) turns each block into a stream, so you get a list of 3 separate streams, which is rarely what you want.
  • flatMap(List::stream) joins the block streams into one stream of all six rooms. The last pipeline flattens each word into its letters, then removes duplicates.

Model answer, spoken: "Use map when each element becomes one value, like a name becoming its length. Use flatMap when each element holds several values you want in one stream, like a list of lists, or the words of many sentences. map(List::stream) would give a stream of streams; flatMap(List::stream) gives one stream of all the items." Revise: map (opens in a new tab) and flatMap (opens in a new tab).

Must know:

  • map(f) where f returns R gives Stream<R>, the same size as before.
  • flatMap(f) where f returns Stream<R> gives one Stream<R>, any size.
  • Typical flatMap uses: List<List<T>>, line.split(" ") words, Optional chains.
  • Primitive versions: flatMapToInt, and mapMulti (Java 16) as a faster cousin.

Predict the output

map or flatMap?

Read each program and pick what it prints.

Round 1 of 4

map on a list of baskets.

import java.util.List;
public class MapOne {
public static void main(String[] args) {
List<List<Integer>> baskets = List.of(List.of(1, 2), List.of(3));
System.out.println(baskets.stream().map(List::size).toList());
}
}
The same idea exists on Optional: map for a function returning a plain value, flatMap for a function that already returns an Optional.

groupingBy with counting, mapping and summing

A downstream collector is the collector that groupingBy applies to each group instead of keeping a list. Examples are counting(), mapping(f, toList()), summingInt(f) and averagingInt(f).

Group students by city and let a downstream collector decide what each group becomes: a list, a count or a total.

Example 2 · groupingBy with three downstream collectors

GroupingDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
public class GroupingDemo {    record Student(String name, String branch, int fee) {}
    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 85000), new Student("Ravi", "ECE", 78000),                new Student("Meena", "CSE", 85000), new Student("Kabir", "MECH", 70000),                new Student("Divya", "ECE", 78000), new Student("Imran", "CSE", 90000));
        Map<String, Long> countByBranch = students.stream()                .collect(Collectors.groupingBy(Student::branch, TreeMap::new, Collectors.counting()));        System.out.println("Count: " + countByBranch);
        Map<String, List<String>> namesByBranch = students.stream()                .collect(Collectors.groupingBy(Student::branch, TreeMap::new,                        Collectors.mapping(Student::name, Collectors.toList())));        System.out.println("Names: " + namesByBranch);
        Map<String, Integer> feesByBranch = students.stream()                .collect(Collectors.groupingBy(Student::branch, TreeMap::new,                        Collectors.summingInt(Student::fee)));        System.out.println("Fees:  " + feesByBranch);    }}
Output
Count: {CSE=3, ECE=2, MECH=1}
Names: {CSE=[Asha, Meena, Imran], ECE=[Ravi, Divya], MECH=[Kabir]}
Fees:  {CSE=260000, ECE=156000, MECH=70000}

What this code does

  • counting() gives a Map<String, Long>, mapping(Student::name, toList()) keeps only the names, and summingInt(Student::fee) adds the fees in each group.
  • Every call passes TreeMap::new, so the branches print in alphabetical order on every run. Without it you get a HashMap with no promised order.

groupingBy(classifier) puts elements into a Map<K, List<T>>, where the key comes from the classifier function. The plain version returns a HashMap, so key order is not guaranteed and can change between runs and Java versions; for sorted output pass a map factory: groupingBy(f, TreeMap::new, downstream). Revise: groupingBy basics (opens in a new tab) and downstream collectors (opens in a new tab).

Must know:

  • groupingBy(f) gives Map<K, List<T>> (a HashMap).
  • groupingBy(f, downstream) changes each group; groupingBy(f, mapFactory, downstream) also picks the map.
  • Downstreams: counting() (Long), summingInt, averagingInt (Double), mapping, maxBy, toSet.
  • Nested grouping: groupingBy(a, groupingBy(b, counting())) gives a map of maps.

Order of execution

Count the words in a sentence

Tap the steps in the order the pipeline does them.

Map<String, Long> freq = Arrays.stream(text.split(" "))
.map(String::toLowerCase)
.collect(groupingBy(w -> w, TreeMap::new, counting()));
System.out.println(freq);

toMap and the duplicate key exception

A merge function is the third argument of toMap. It decides what to keep when two elements give the same key: keep the old value, keep the new one, add them or join them.

Two contacts are both called Asha. See the exact error toMap gives, then two ways to fix it.

Example 3 · toMap: the duplicate key error and two fixes

ToMapDuplicateDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
public class ToMapDuplicateDemo {    record Contact(String name, String phone) {}
    public static void main(String[] args) {        List<Contact> contacts = List.of(                new Contact("Asha", "98100"),                new Contact("Ravi", "98200"),                new Contact("Asha", "98300"));
        try {            Map<String, String> byName = contacts.stream()                    .collect(Collectors.toMap(Contact::name, Contact::phone));            System.out.println(byName);        } catch (IllegalStateException e) {            System.out.println("Error: " + e.getMessage());        }
        Map<String, String> latest = contacts.stream()                .collect(Collectors.toMap(Contact::name, Contact::phone,                        (oldPhone, newPhone) -> newPhone, LinkedHashMap::new));        System.out.println("Keep latest: " + latest);
        Map<String, String> all = contacts.stream()                .collect(Collectors.toMap(Contact::name, Contact::phone,                        (a, b) -> a + "," + b, TreeMap::new));        System.out.println("Keep all:    " + all);    }}
Output
Error: Duplicate key Asha (attempted merging values 98100 and 98300)
Keep latest: {Asha=98300, Ravi=98200}
Keep all:    {Asha=98100,98300, Ravi=98200}

What this code does

  • Two contacts are named Asha, so the two-argument toMap throws IllegalStateException with the key and both values in the message.
  • The merge function (oldPhone, newPhone) -> newPhone keeps the latest value; (a, b) -> a + "," + b keeps both. The fourth argument chooses LinkedHashMap (insertion order) or TreeMap (sorted keys).

toMap(keyFn, valueFn) builds a map with one entry per element. If two elements give the same key it throws IllegalStateException: Duplicate key ...; on Java 9 and later the message also shows both values. Revise: toMap and duplicate keys (opens in a new tab).

Must know:

  • toMap(k, v, merge) resolves duplicates: (a, b) -> b, (a, b) -> a, Integer::sum.
  • toMap(k, v, merge, LinkedHashMap::new) keeps insertion order; the fourth argument picks the map type.
  • A null value makes toMap throw NullPointerException.
  • Many values per key? Use groupingBy, not toMap.

Find the bug

Find the toMap bug

Each snippet should work. Tap the wrong line, then check the fix.

Two contacts can have the same name.

Round 1 of 3

partitioningBy, joining, and reduce vs collect

partitioningBy splits elements into exactly two groups, true and false, using a predicate. Both keys are always in the map, even when one group is empty.

Split results into passed and failed, join names into one line, then compare reduce with collect.

Example 4 · partitioningBy and joining

PartitionJoinDemo.javaJava
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
public class PartitionJoinDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 35, 88, 39, 64);
        Map<Boolean, List<Integer>> split = marks.stream()                .collect(Collectors.partitioningBy(m -> m >= 40));        System.out.println("partitioningBy: " + split);
        Map<Boolean, Long> counts = marks.stream()                .collect(Collectors.partitioningBy(m -> m >= 90, Collectors.counting()));        System.out.println("Distinction count: " + counts);
        String line = marks.stream()                .map(String::valueOf)                .collect(Collectors.joining(", ", "Marks: [", "]"));        System.out.println(line);    }}
Output
partitioningBy: {false=[35, 39], true=[72, 88, 64]}
Distinction count: {false=5, true=0}
Marks: [72, 35, 88, 39, 64]

What this code does

  • partitioningBy always returns both keys, false and true. The distinction count shows true=0: an empty group is still present, unlike groupingBy.
  • joining(", ", "Marks: [", "]") adds the delimiter between elements and the prefix and suffix once. Elements must be strings, so map(String::valueOf) comes first.

Example 5 · reduce for one value, collect for a container

ReduceVsCollectDemo.javaJava
import java.util.List;import java.util.Optional;import java.util.stream.Collectors;
public class ReduceVsCollectDemo {    public static void main(String[] args) {        List<Integer> payments = List.of(250, 120, 480, 60);
        int total = payments.stream().reduce(0, Integer::sum);        Optional<Integer> biggest = payments.stream().reduce(Integer::max);        System.out.println("reduce sum: " + total + ", reduce max: " + biggest.orElse(0));
        List<Integer> big = payments.stream()                .filter(p -> p > 100)                .collect(Collectors.toList());        System.out.println("collect to list: " + big);
        StringBuilder receipt = payments.stream()                .collect(StringBuilder::new,                        (sb, p) -> sb.append(p).append(';'),                        StringBuilder::append);        System.out.println("collect to StringBuilder: " + receipt);
        int viaInt = payments.stream().mapToInt(Integer::intValue).sum();        System.out.println("mapToInt sum: " + viaInt);    }}
Output
reduce sum: 910, reduce max: 480
collect to list: [250, 120, 480]
collect to StringBuilder: 250;120;480;60;
mapToInt sum: 910

What this code does

  • reduce(0, Integer::sum) has an identity, so it returns an int; reduce(Integer::max) has none, so it returns an Optional in case the stream is empty.
  • The three-argument collect builds a mutable StringBuilder: a supplier, an accumulator and a combiner (used by parallel streams). For plain sums, mapToInt(...).sum() is the clearest.

joining(delimiter, prefix, suffix) joins strings into one String. reduce combines elements into one immutable value, like a sum or a maximum: reduce(0, Integer::sum). collect builds a mutable container such as a List, Map or StringBuilder. Using reduce for string concatenation creates a new string at every step; joining is simpler and faster. Revise: partitioningBy (opens in a new tab) and reduce basics (opens in a new tab).

Must know:

  • partitioningBy always has both true and false keys.
  • joining() needs a Stream<String>; add map(String::valueOf) for numbers.
  • reduce(identity, op) returns T; reduce(op) returns Optional<T>.
  • collect is for containers (List, Map, StringBuilder); reduce is for one immutable value.

Fix the error

Fix the collector compile errors

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Add up the fees.

import java.util.List;
public class FixReduce {
public static void main(String[] args) {
List<Integer> fees = List.of(120, 80, 50);
int total = fees.stream().reduce(Integer::sum);
System.out.println(total);
}
}

Error

FixReduce.java:6: error: incompatible types: Optional<Integer> cannot be converted to int
        int total = fees.stream().reduce(Integer::sum);
                                        ^

Next step

Check your understanding

12 quick questions