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 1) — Interview Questions

Ten hands-on Stream API problems — filter evens, max, sum, uppercase, sort, count, distinct, reduce, findAny and extracting first names — with correct solutions, edge cases and the follow-ups interviewers ask.

Published September 25, 2026


How to use this lesson

In a live coding round you'll often be asked to "solve it with streams". Write the pipeline, then say one sentence about each operation, and mention an edge case (empty list, nulls, ties). All the examples use this data:

List<Integer> numbers = List.of(4, 9, 1, 12, 7, 4, 6);
List<String> names = List.of("Asha Rao", "Vikram  Singh", "Meera Iyer");

stream.toList() (Java 16+) returns an unmodifiable list. Use collect(Collectors.toList()) on Java 8–15, or when the caller needs to modify the result.

Q1. Filter the even numbers from a list.

List<Integer> evens = numbers.stream()
        .filter(n -> n % 2 == 0)
        .toList();                           // [4, 12, 4, 6]

Explain: filter keeps the elements that match the predicate, and toList collects them.

Key points to cover:

  • n % 2 == 0 works for negative numbers too. The odd check is the one to be careful with: n % 2 == 1 fails for negative odd numbers (−3 % 2 is −1). Use n % 2 != 0.
  • For a primitive int[]: Arrays.stream(arr).filter(n -> n % 2 == 0).toArray(), which avoids boxing.

Learn it in depth → Streams API

Q2. Find the maximum value.

Optional<Integer> max = numbers.stream().max(Comparator.naturalOrder());   // Optional[12]
int maxOrZero = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);

Explain: max takes a comparator and returns an Optional, because the list might be empty.

Key points to cover:

  • Integer::compare also works as the comparator.
  • Don't write (a, b) -> a - b, because subtraction can overflow.
  • For the element with the highest property: employees.stream().max(Comparator.comparing(Employee::salary)).

Q3. Calculate the sum of the elements.

int sum = numbers.stream().mapToInt(Integer::intValue).sum();     // 43
long safeSum = numbers.stream().mapToLong(Integer::longValue).sum();

Explain: mapToInt converts to an IntStream, which has sum(), average() and friends, with no boxing.

Key points to cover:

  • Use mapToLong when the total could exceed Integer.MAX_VALUE. IntStream.sum() overflows silently.
  • For money, sum BigDecimals with reduce(BigDecimal.ZERO, BigDecimal::add).

Q4. Convert a list of names to uppercase.

List<String> upper = names.stream()
        .map(n -> n.toUpperCase(Locale.ROOT))
        .toList();

Explain: map transforms each element, and the result has the same size.

Key points to cover:

  • Pass a Locale for predictable results. "title".toUpperCase() behaves unexpectedly in a Turkish locale (dotted/dotless i). String::toUpperCase is fine for a quick answer.

Q5. Sort a list in ascending (and descending) order.

List<Integer> asc  = numbers.stream().sorted().toList();                              // [1, 4, 4, 6, 7, 9, 12]
List<Integer> desc = numbers.stream().sorted(Comparator.reverseOrder()).toList();     // [12, 9, 7, 6, 4, 4, 1]
List<Employee> bySalaryThenName = employees.stream()
        .sorted(Comparator.comparing(Employee::salary).reversed().thenComparing(Employee::name))
        .toList();

Explain: sorted() uses the natural order. Pass a comparator for a custom order.

Key points to cover:

  • sorted is a stateful intermediate operation: it has to buffer every element before it emits any.
  • It doesn't change the source list. To sort in place, use list.sort(...) on a mutable list.

Learn it in depth → Collectors

Q6. Count the elements greater than 5.

long count = numbers.stream().filter(n -> n > 5).count();    // 4 (9, 12, 7, 6)

Explain: count is a terminal operation that returns a long.

Key points to cover:

  • Since Java 9, count() may skip running the pipeline entirely if it can compute the size directly, for example on a sized stream with no filter. So side effects in peek or map might not run. Don't rely on them.

Q7. Get the distinct elements.

List<Integer> unique = numbers.stream().distinct().toList();     // [4, 9, 1, 12, 7, 6]: first-seen order kept

Explain: distinct removes duplicates using equals/hashCode, and it keeps encounter order for ordered streams.

Key points to cover:

  • For custom objects, distinct relies on equals/hashCode. To deduplicate by a property, collect into a map: toMap(Employee::email, e -> e, (a, b) -> a), then take .values().

Q8. Reduce a list to its sum using reduce.

int total = numbers.stream().reduce(0, Integer::sum);           // 43
Optional<Integer> product = numbers.stream().reduce((a, b) -> a * b);

Explain: reduce(identity, accumulator) folds the elements into one value, starting from the identity.

Key points to cover:

  • The identity must be neutral for the operation: 0 for addition, 1 for multiplication.
  • The accumulator must be associative, so the reduction also works in parallel.
  • The version without an identity returns an Optional, because the stream could be empty.
  • For sums, mapToInt(...).sum() is clearer and avoids boxing.

Q9. Return any element from the list.

Optional<Integer> any = numbers.stream().findAny();

Explain: findAny returns some element. It short-circuits, and it's empty for an empty stream.

Key points to cover:

  • On a sequential stream it usually returns the first element, but that isn't guaranteed. On a parallel stream it returns whichever element is found first, which is faster than findFirst.
  • Use findFirst when the order matters.

Q10. Extract the first names from a list of full names.

List<String> firstNames = names.stream()
        .map(String::strip)
        .filter(n -> !n.isEmpty())
        .map(n -> n.split("\\s+")[0])
        .toList();                                                  // [Asha, Vikram, Meera]

Explain: split each name on whitespace, and take the first part.

Key points to cover:

  • split(" ") breaks on double spaces ("Vikram Singh"), and "".split(...) still returns one element. The regex \\s+ together with strip handles messy input.
  • An alternative without regex: n.substring(0, n.indexOf(' ')), but that fails when there's no space, so guard it.

Follow-up questions this topic invites — and their answers

Q: What's the difference between Collectors.toList() and Stream.toList()? A: Stream.toList() (Java 16) returns an unmodifiable list, and allows null elements. Collectors.toList() returns a mutable ArrayList in practice, although that isn't guaranteed by its contract. Use Collectors.toCollection(ArrayList::new) when you need a specific mutable type.

Q: How do you find the second-highest number with streams? A: numbers.stream().distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst(). It returns an Optional, which is empty if there are fewer than two distinct values.

Q: How do you get the average? A: numbers.stream().mapToInt(Integer::intValue).average(), which returns an OptionalDouble. Or Collectors.averagingInt(...) inside a collect.

Q: Can a stream be reused? A: No. After a terminal operation it's consumed, and reusing it throws an IllegalStateException. Create a new stream from the source, or use a Supplier<Stream<T>>.

Previous

Java 8 to Java 21 Features — Interview Questions

Next

Stream API Coding Questions (Part 2) — Interview Questions

AI Tutor

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

Quick actions

AI responses can be inaccurate. Verify critical information.