Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsJava 8+ & Stream API
✓ FreeBeginner· 6 min read

Stream API Coding Questions (Part 2) — Interview Questions

allMatch, noneMatch, findFirst, flatMap, groupingBy, peek, limit, skip, collecting to a Set and summary statistics — solutions, pitfalls and follow-ups.

Published September 25, 2026


How to use this lesson

These questions cover matching, flattening, grouping and statistics, which are the operations that come up when streams meet real data. The sample data:

List<Integer> numbers = List.of(4, 9, 1, 12, 7, 4, 6);
record User(String name, int age, String city) { }
List<User> users = List.of(new User("Asha", 28, "Pune"), new User("Ravi", 34, "Delhi"),
                           new User("Meera", 28, "Delhi"), new User("Kabir", 41, "Pune"));

Q1. Check whether all numbers are positive.

boolean allPositive = numbers.stream().allMatch(n -> n > 0);   // true

Explain: allMatch short-circuits at the first element that fails.

Key points to cover:

  • Edge case: allMatch on an empty stream returns true ("vacuous truth"). If an empty list should count as a failure, check isEmpty() first.

Learn it in depth → Streams API

Q2. Check that there are no negative numbers.

boolean noNegatives = numbers.stream().noneMatch(n -> n < 0);  // true

Key points to cover:

  • noneMatch(p) is equivalent to !anyMatch(p).
  • It also returns true for an empty stream.
  • anyMatch returns false for an empty stream.

Q3. Find the first element.

Optional<Integer> first = numbers.stream().findFirst();                          // Optional[4]
Optional<User> firstAdult = users.stream().filter(u -> u.age() >= 30).findFirst(); // Ravi

Explain: findFirst respects encounter order, and short-circuits.

Key points to cover:

  • findFirst throws a NullPointerException if the first element is null, because an Optional can't hold null. Filter out nulls first when your data may contain them.

Q4. Flatten a nested list.

List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3, 4, 5), List.of());
List<Integer> flat = nested.stream().flatMap(List::stream).toList();   // [1, 2, 3, 4, 5]

Explain: flatMap maps each inner list to a stream, and concatenates the streams into one.

Key points to cover:

  • Real-world example: all the order lines from a list of orders, orders.stream().flatMap(o -> o.lines().stream()).
  • Java 16's mapMulti is an alternative that avoids creating a stream per element.

Q5. Group users by age (and more).

Map<Integer, List<User>> byAge = users.stream()
        .collect(Collectors.groupingBy(User::age));
// {28=[Asha, Meera], 34=[Ravi], 41=[Kabir]} (HashMap: no guaranteed order)

Map<String, Long> countByCity = users.stream()
        .collect(Collectors.groupingBy(User::city, TreeMap::new, Collectors.counting()));
// {Delhi=2, Pune=2}: sorted keys, because we asked for a TreeMap

Map<String, List<String>> namesByCity = users.stream()
        .collect(Collectors.groupingBy(User::city, Collectors.mapping(User::name, Collectors.toList())));

Explain: groupingBy(classifier) builds a map from each key to the list of matching elements. The second and third arguments let you choose the map type and a downstream collector (counting, mapping, summingInt, averagingDouble, maxBy).

Key points to cover:

  • partitioningBy(predicate) is the special case with two groups: Map<Boolean, List<T>>.

Learn it in depth → Collectors

Q6. Print elements during processing without altering the stream.

List<Integer> result = numbers.stream()
        .filter(n -> n > 5)
        .peek(n -> log.debug("passed filter: {}", n))
        .map(n -> n * 10)
        .toList();

Explain: peek runs an action on each element as it flows past, and passes the element on unchanged. It's meant for debugging.

Key points to cover:

  • peek is lazy. Without a terminal operation nothing is printed.
  • Some terminal operations can skip it entirely, for example count() on a sized stream.
  • Don't use peek for business side effects, such as saving to a database or modifying state. Use forEach, or a proper loop.

Q7. Limit the output to the first three elements.

List<Integer> firstThree = numbers.stream().limit(3).toList();     // [4, 9, 1]

Key points to cover:

  • limit is short-circuiting, so it even works on infinite streams: Stream.iterate(1, n -> n * 2).limit(10).
  • On ordered parallel streams, limit can be expensive, because it must preserve encounter order.
  • Pagination pattern: skip(page * size).limit(size).

Q8. Skip the first two elements.

List<Integer> rest = numbers.stream().skip(2).toList();            // [1, 12, 7, 4, 6]

Key points to cover:

  • Skipping more elements than exist gives an empty stream, not an error.
  • dropWhile and takeWhile (Java 9) skip or take elements while a condition holds. That's useful on sorted data.

Q9. Convert a list to a Set to remove duplicates.

Set<Integer> unique = numbers.stream().collect(Collectors.toSet());                 // no order guarantee
Set<Integer> ordered = numbers.stream().collect(Collectors.toCollection(LinkedHashSet::new));
Set<Integer> sorted = new TreeSet<>(numbers);                                       // no stream needed

Key points to cover:

  • Collectors.toSet() currently gives a HashSet, but that's not guaranteed. Use toCollection(...) for a specific type, or Collectors.toUnmodifiableSet() for an immutable one.
  • For a plain conversion, new HashSet<>(list) or Set.copyOf(list) is simpler than a stream.

Q10. Get summary statistics (min, max, average, sum, count).

IntSummaryStatistics stats = numbers.stream().mapToInt(Integer::intValue).summaryStatistics();
stats.getMin();      // 1
stats.getMax();      // 12
stats.getAverage();  // 6.142857…
stats.getSum();      // 43 (a long, so no int overflow)
stats.getCount();    // 7

DoubleSummaryStatistics ageStats = users.stream().collect(Collectors.summarizingDouble(User::age));

Explain: summaryStatistics computes all five values in a single pass, which is more efficient than five separate streams.

Key points to cover:

  • For an empty stream: min is Integer.MAX_VALUE, max is Integer.MIN_VALUE, average is 0, and count is 0. Check getCount() before trusting the values.

Follow-up questions this topic invites — and their answers

Q: How do you count word frequencies with streams? A: Arrays.stream(text.toLowerCase().split("\\W+")).filter(w -> !w.isBlank()).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).

Q: How do you convert a list to a map, and what happens with duplicate keys? A: list.stream().collect(Collectors.toMap(User::name, User::age)). It throws an IllegalStateException on a duplicate key unless you pass a merge function: toMap(k, v, (a, b) -> a). It also throws an NPE for null values.

Q: What's the difference between groupingBy and partitioningBy? A: partitioningBy always produces exactly two keys (true and false), even if one group is empty. groupingBy creates a key only for the values that actually occur.

Q: Is forEach guaranteed to process elements in order? A: Not on parallel streams. Use forEachOrdered when order matters, at some cost to parallelism.

Previous

Stream API Coding Questions (Part 1) — Interview Questions

Next

Classic Number & String Programs — Interview Questions

AI Tutor

Lesson: Stream API Coding Questions (Part 2) — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.