LearnFrenzy
Sign in Take a free test

Java Programming · Topic 22 of 28

Streams API

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Streams API · Study material

Advanced collectors: nested grouping, collectingAndThen, teeing

Collectors can be nested to build multi-level reports, post-processed with collectingAndThen, or run side by side with teeing.

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 Sale(String region, String product, int qty, double price) {
    double total() { return qty * price; }
}

public class Main {
    public static void main(String[] args) {
        List<Sale> sales = List.of(new Sale("North", "Pen", 100, 10), new Sale("South", "Book", 20, 150), new Sale("North", "Book", 10, 150),
                                   new Sale("South", "Pen", 300, 10), new Sale("West", "Bag", 5, 900), new Sale("North", "Bag", 2, 900));

        // Nested grouping: region → product → total revenue
        Map<String, Map<String, Double>> byRegion = sales.stream().collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                Collectors.groupingBy(Sale::product, TreeMap::new, Collectors.summingDouble(Sale::total))));
        System.out.println(byRegion);

        // Best sale per region, unwrapped from Optional with collectingAndThen
        Map<String, String> best = sales.stream().collect(Collectors.groupingBy(Sale::region, TreeMap::new,
                Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingDouble(Sale::total)), o -> o.map(Sale::product).orElse("-"))));
        System.out.println(best);

        // teeing (Java 12): two collectors at once, then combine
        String summary = sales.stream().collect(Collectors.teeing(
                Collectors.summingDouble(Sale::total), Collectors.counting(), (sum, n) -> "revenue " + sum + " from " + n + " sales"));
        System.out.println(summary);

        Optional<String> topProduct = sales.stream().collect(Collectors.groupingBy(Sale::product, Collectors.summingInt(Sale::qty)))
                .entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);
        System.out.println(topProduct.orElse("-"));
    }
}

Output

{North={Bag=1800.0, Book=1500.0, Pen=1000.0}, South={Book=3000.0, Pen=3000.0}, West={Bag=4500.0}}
{North=Bag, South=Book, West=Bag}
revenue 14800.0 from 6 sales
Pen

Parallel streams – use with care

// Parallel streams split the work across CPU cores (the common ForkJoinPool)
long primes = IntStream.rangeClosed(2, 5_000_000).parallel().filter(Main::isPrime).count();

// ✔ Good candidates: large data, CPU-heavy, independent elements, no shared mutable state
// ✘ Avoid: small lists, I/O, ordering requirements, side effects:
List<Integer> unsafe = new ArrayList<>();
IntStream.range(0, 1000).parallel().forEach(unsafe::add);      // ✘ data race: wrong size or exception
List<Integer> safe = IntStream.range(0, 1000).parallel().boxed().toList();   // ✔ let the stream build the result
// forEach on a parallel stream does not keep order; use forEachOrdered if order matters.

Loop to stream: common translations

// count matching         for … if … count++           →  list.stream().filter(p).count()
// transform              for … out.add(f(x))          →  list.stream().map(f).toList()
// sum of a property      for … total += o.amount()    →  list.stream().mapToDouble(Order::amount).sum()
// find first             for … if … return x          →  list.stream().filter(p).findFirst()
// any / all              for … if … return true       →  anyMatch(p) / allMatch(p)
// group                  map.computeIfAbsent(k, …).add →  collect(groupingBy(keyFn))
// join strings           StringBuilder + separator     →  map(String::valueOf).collect(joining(", "))
// distinct, sorted       Set + sort                    →  distinct().sorted()
// nested loops           for a … for b …               →  flatMap(a -> bs.stream().map(b -> …))

Streams checklist

  • Keep each step simple; one operation per line.
  • Prefer method references (Order::amount) where they read well.
  • Avoid side effects; build results with collect or toList.
  • Use primitive streams for numeric work.
  • Handle Optional results explicitly.
  • Pass a map factory (TreeMap::new) to groupingBy/toMap when order matters.
  • Give toMap a merge function if keys can repeat.
  • Use parallel() only after measuring.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links