map vs flatMap, groupingBy and Collectors
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)"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.
Example 1 · map vs flatMap on a list of lists
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); }}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)wherefreturnsRgivesStream<R>, the same size as before.flatMap(f)wherefreturnsStream<R>gives oneStream<R>, any size.- Typical
flatMapuses:List<List<T>>,line.split(" ")words,Optionalchains. - Primitive versions:
flatMapToInt, andmapMulti(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.
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
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); }}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 aMap<String, Long>,mapping(Student::name, toList())keeps only the names, andsummingInt(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 aHashMapwith 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)givesMap<K, List<T>>(aHashMap).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.
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
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); }}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
toMapthrowsIllegalStateExceptionwith the key and both values in the message. - The merge function
(oldPhone, newPhone) -> newPhonekeeps the latest value;(a, b) -> a + "," + bkeeps both. The fourth argument choosesLinkedHashMap(insertion order) orTreeMap(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
nullvalue makestoMapthrowNullPointerException. - Many values per key? Use
groupingBy, nottoMap.
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 3partitioningBy, 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
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); }}partitioningBy: {false=[35, 39], true=[72, 88, 64]}
Distinction count: {false=5, true=0}
Marks: [72, 35, 88, 39, 64]What this code does
partitioningByalways returns both keys,falseandtrue. The distinction count showstrue=0: an empty group is still present, unlikegroupingBy.joining(", ", "Marks: [", "]")adds the delimiter between elements and the prefix and suffix once. Elements must be strings, somap(String::valueOf)comes first.
Example 5 · reduce for one value, collect for a container
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); }}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 anint;reduce(Integer::max)has none, so it returns anOptionalin case the stream is empty.- The three-argument
collectbuilds a mutableStringBuilder: 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:
partitioningByalways has bothtrueandfalsekeys.joining()needs aStream<String>; addmap(String::valueOf)for numbers.reduce(identity, op)returnsT;reduce(op)returnsOptional<T>.collectis for containers (List,Map,StringBuilder);reduceis 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.
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