Skip to lesson

joining, mapping and filtering collectors

Collectors.joining glues a stream of strings into one string, with a separator between them and an optional start and end. mapping, filtering, flatMapping and collectingAndThen are collectors that change, filter, expand or finish the values inside each group.

joining: from many strings to one

A CSV line, a report header and a WhatsApp message listing names all need the same thing: values with a comma between them, but no comma at the end. The old StringBuilder loop either left a trailing comma or needed an if to skip it.

Example 1 · joining: the StringBuilder way and the collector way

JoiningDemo.javaJava
import java.util.List;import java.util.stream.Collectors;
public class JoiningDemo {    public static void main(String[] args) {        List<String> names = List.of("Asha", "Ravi", "Neha");
        // old way: a loop that must skip the last comma        StringBuilder sb = new StringBuilder();        for (int i = 0; i < names.size(); i++) {            sb.append(names.get(i));            if (i < names.size() - 1) {                sb.append(", ");            }        }        System.out.println("Loop: " + sb);
        System.out.println("joining():        " + names.stream().collect(Collectors.joining()));        System.out.println("joining(\", \"):    " + names.stream().collect(Collectors.joining(", ")));        System.out.println("With brackets:    "                + names.stream().collect(Collectors.joining(", ", "[", "]")));
        List<String> nobody = List.of();        System.out.println("Empty list:       "                + nobody.stream().collect(Collectors.joining(", ", "[", "]")));    }}
Output
Loop: Asha, Ravi, Neha
joining():        AshaRaviNeha
joining(", "):    Asha, Ravi, Neha
With brackets:    [Asha, Ravi, Neha]
Empty list:       []

What this code does

  • joining(", ") puts the delimiter only between neighbours, so there is no trailing comma to remove. The prefix and suffix are added once, around the whole result.
  • With no names at all, the result is only the prefix and suffix, []. joining() with no arguments glues the names with nothing in between.
  • Why joining: with a StringBuilder you must remember to skip the last comma. The collector puts the delimiter only between neighbours, so that bug cannot happen.

Example 2 · A CSV header and CSV lines from records

CsvDemo.javaJava
import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;
record Student(int roll, String name, int marks) {}
public class CsvDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student(101, "Asha", 88),                new Student(102, "Ravi", 72),                new Student(103, "Neha", 91));
        String header = Stream.of("roll", "name", "marks")                .collect(Collectors.joining(","));        System.out.println(header);
        for (Student s : students) {            String line = Stream.of(s.roll(), s.name(), s.marks())                    .map(String::valueOf)                    .collect(Collectors.joining(","));            System.out.println(line);        }
        String rolls = students.stream()                .map(s -> String.valueOf(s.roll()))                .collect(Collectors.joining(" | ", "Rolls: ", "."));        System.out.println(rolls);    }}
Output
roll,name,marks
101,Asha,88
102,Ravi,72
103,Neha,91
Rolls: 101 | 102 | 103.

What this code does

  • A CSV line is just fields joined with commas. roll and marks are numbers, so map(String::valueOf) turns every field into a String before joining sees it.
  • The last line uses all three arguments: | between the roll numbers, Rolls: before them and a full stop after them.

joining() glues strings with nothing between them. joining(", ") puts a delimiter, the separator text, between neighbours only. joining(", ", "[", "]") also adds a prefix at the start and a suffix at the end. joining works only on a stream of strings (or other character sequences). For numbers or objects, map them to strings first, for example .map(String::valueOf) or .map(Student::name).

On an empty stream, joining(", ", "[", "]") returns just the prefix and suffix: "[]". joining(", ") returns an empty string.

mapping inside groupingBy

groupingBy(Student::branch) gives whole Student objects per branch, but a notice board needs only names. mapping(Student::name, toList()) changes each student into a name before it reaches the list, so the result is Map<String, List<String>>.

Example 3 · mapping inside groupingBy: names per branch

NamesPerBranchDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int marks) {}
public class NamesPerBranchDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 88),                new Student("Ravi", "ECE", 72),                new Student("Neha", "CSE", 91),                new Student("Imran", "MECH", 64),                new Student("Kiran", "ECE", 79),                new Student("Divya", "CSE", 70));
        Map<String, List<String>> names = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.mapping(Student::name, Collectors.toList())));        System.out.println(new TreeMap<>(names));
        Map<String, String> board = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.mapping(Student::name, Collectors.joining(", "))));        new TreeMap<>(board).forEach((b, line) -> System.out.println(b + ": " + line));    }}
Output
{CSE=[Asha, Neha, Divya], ECE=[Ravi, Kiran], MECH=[Imran]}
CSE: Asha, Neha, Divya
ECE: Ravi, Kiran
MECH: Imran

What this code does

  • mapping(Student::name, toList()) keeps only the names, so the map is Map<String, List<String>> instead of whole student objects.
  • Swapping toList() for joining(", ") makes each group a finished line of text, ready for a notice board or a message.

Combine it with joining and each group becomes one ready-to-print line: groupingBy(Student::branch, mapping(Student::name, joining(", "))) gives CSE=Asha, Neha, Divya.

filtering and flatMapping (Java 9)

filter before groupingBy removes elements before any group exists. If no MECH student scored 75 or more, MECH vanishes from the result. filtering(predicate, downstream) keeps every group and filters inside it, so MECH stays with an empty list or a count of 0.

Example 4 · filtering keeps empty groups; filter removes them

DistinctionDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int marks) {}
public class DistinctionDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 88),                new Student("Ravi", "ECE", 72),                new Student("Neha", "CSE", 91),                new Student("Imran", "MECH", 64),                new Student("Kiran", "ECE", 79));
        Map<String, Long> filteredFirst = students.stream()                .filter(s -> s.marks() >= 75)                .collect(Collectors.groupingBy(Student::branch, Collectors.counting()));        System.out.println("filter first:   " + new TreeMap<>(filteredFirst));
        Map<String, Long> filteredInside = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.filtering(s -> s.marks() >= 75, Collectors.counting())));        System.out.println("filtering:      " + new TreeMap<>(filteredInside));
        Map<String, List<String>> names = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.filtering(s -> s.marks() >= 75,                                Collectors.mapping(Student::name, Collectors.toList()))));        System.out.println("Distinction:    " + new TreeMap<>(names));    }}
Output
filter first:   {CSE=2, ECE=1}
filtering:      {CSE=2, ECE=1, MECH=0}
Distinction:    {CSE=[Asha, Neha], ECE=[Kiran], MECH=[]}

What this code does

  • With filter first, Imran is removed before grouping, so MECH never becomes a key and the report silently forgets the branch.
  • filtering groups everyone first, then filters inside each group, so MECH stays with a count of 0 and an empty name list. Downstream collectors nest: filtering wraps mapping, which wraps toList().

Example 5 · flatMapping: all electives taken in each branch

ElectivesDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.TreeSet;import java.util.stream.Collectors;
record Student(String name, String branch, List<String> electives) {}
public class ElectivesDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", List.of("AI", "Cloud")),                new Student("Ravi", "ECE", List.of("IoT", "VLSI")),                new Student("Neha", "CSE", List.of("Cloud", "Security")),                new Student("Kiran", "ECE", List.of("IoT")));
        Map<String, List<List<String>>> nested = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.mapping(Student::electives, Collectors.toList())));        System.out.println("mapping:     " + new TreeMap<>(nested));
        Map<String, TreeSet<String>> flat = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.flatMapping(s -> s.electives().stream(),                                Collectors.toCollection(TreeSet::new))));        System.out.println("flatMapping: " + new TreeMap<>(flat));    }}
Output
mapping:     {CSE=[[AI, Cloud], [Cloud, Security]], ECE=[[IoT, VLSI], [IoT]]}
flatMapping: {CSE=[AI, Cloud, Security], ECE=[IoT, VLSI]}

What this code does

  • mapping(Student::electives, toList()) gives a list of lists per branch, which is awkward to use. Each student's electives stay boxed in their own list.
  • flatMapping(s -> s.electives().stream(), ...) opens each student's list and pours every elective into one TreeSet per branch, so Cloud appears once for CSE and the set is sorted.

flatMapping(function, downstream) is for elements that hold several values. The function turns each element into a stream, and every value of that stream goes into the downstream collector. Students with a list of elective subjects become, per branch, the set of all electives taken. Both were added in Java 9. They match filter and flatMap on streams, but work per group.

collectingAndThen: one last step

collectingAndThen(downstream, finisher) runs a collector, then passes its result through one more function, the finisher. It answers the small "and then" needs at the end of a collect.

Example 6 · collectingAndThen: read-only lists, no Optional, int counts

FinisherDemo.javaJava
import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int marks) {}
public class FinisherDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 88),                new Student("Ravi", "ECE", 72),                new Student("Neha", "CSE", 91),                new Student("Kiran", "ECE", 79));
        Map<String, Student> toppers = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.collectingAndThen(                                Collectors.maxBy(Comparator.comparingInt(Student::marks)),                                Optional::get)));        new TreeMap<>(toppers).forEach((b, s) -> System.out.println(b + " topper: " + s.name()));
        Map<String, Integer> sizes = students.stream()                .collect(Collectors.groupingBy(Student::branch,                        Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));        System.out.println("Sizes: " + new TreeMap<>(sizes));
        List<String> names = students.stream()                .map(Student::name)                .collect(Collectors.collectingAndThen(Collectors.toList(),                        Collections::unmodifiableList));        try {            names.add("Zoya");        } catch (UnsupportedOperationException e) {            System.out.println("names is read-only: " + names);        }    }}
Output
CSE topper: Neha
ECE topper: Kiran
Sizes: {CSE=2, ECE=2}
names is read-only: [Asha, Ravi, Neha, Kiran]

What this code does

  • collectingAndThen(maxBy(...), Optional::get) unwraps each group's Optional, so the map holds Student values directly. It is safe because a group is never empty.
  • Long::intValue turns each count into an Integer, and Collections::unmodifiableList makes the final list read-only. Each finisher runs once, after its collector has finished.
  • Make the result read-only: collectingAndThen(toList(), Collections::unmodifiableList).
  • Unwrap the Optional of maxBy inside groupingBy: collectingAndThen(maxBy(cmp), Optional::get).
  • Turn a count into an int: collectingAndThen(counting(), Long::intValue).
  • Pick one value from a group, such as the size of a set: collectingAndThen(toSet(), Set::size).

Next step

Check your understanding

11 quick questions