200 Java Stream API Interview Questions with Code and Output (2026)
If you are preparing for a Java developer, Spring Boot, backend, microservices, or senior Java interview, the Java Stream API is one of the topics you should be comfortable with.
Interviewers rarely stop at asking what filter() or map() does. They often move quickly into practical coding questions such as:
- Find duplicate elements using Streams
- Find the first non-repeating character
- Find the second-highest salary
- Find the highest-paid employee in each department
- Group employees by department
- Find employees earning above the average salary
- Explain
map()vsflatMap() - Explain lazy evaluation
- Explain intermediate vs terminal operations
- Use
reduce()correctly - Explain parallel Stream pitfalls
- Solve collection problems without writing traditional loops
This guide contains 200 Java Stream API interview questions with Java code and expected output. The questions progress from beginner fundamentals to practical employee, salary, grouping, collector, Optional, and parallel Stream problems.
The examples are written for modern Java. Most work with Java 17+. Examples using Stream.toList() require Java 16 or later.
For broader interview preparation, you can also read our TCS Interview Questions 2026 guide or the complete Interview Assistant guide.
What You Will Learn
This article covers:
- Java Stream basics
filter(),map(), and transformationsflatMap()- String and character problems
- Sorting and duplicate handling
- Numeric Streams and
reduce() - Collectors
groupingBy()andpartitioningBy()- Employee and salary interview problems
- Optional and primitive Streams
- Lazy evaluation and short-circuiting
- Parallel Streams
- Stream performance and common pitfalls
- Real interview-style coding problems
Common Imports Used in the Examples
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
200 Java Stream API Interview Questions with Code and Output (2026)
Java Stream API questions are repeatedly reported in Java backend interviews, especially for roles involving Java 8+, Spring Boot, microservices, collections, and functional programming.
This collection contains 200 practical Java Stream interview questions, each with:
- The interview question
- A concise explanation
- Java code
- Expected output
- An interview follow-up or key point where useful
The set is adapted and randomized from recurring patterns in publicly reported Java interview experiences and Stream interview-preparation sets. The wording and examples are original rather than copied verbatim. Public interview reports include Stream questions such as finding employees by name prefix, highest salary by department, employees above average salary, chaining filters, finding duplicates, non-repeating characters, map() vs flatMap(), skip()/limit(), and general Stream API concepts.
Most examples use Java 17+ syntax. Snippets using Stream.toList() require Java 16+.
Common imports
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
1. What is the Java Stream API?
A Stream is a pipeline for processing a sequence of elements. It does not store elements; it processes elements from a source such as a collection.
List<Integer> nums = List.of(1, 2, 3);
nums.stream().forEach(System.out::println);
Output
1
2
3
Interview follow-up: How is a Stream different from a Collection?
2. How do you create a Stream from a List?
Call stream() on the collection.
List<String> names = List.of("Amit", "Riya", "Kabir");
names.stream().forEach(System.out::println);
Output
Amit
Riya
Kabir
3. How do you create a Stream with Stream.of()?
Stream.of() creates a finite stream from the supplied elements.
Stream.of("Java", "Spring", "SQL").forEach(System.out::println);
Output
Java
Spring
SQL
4. How do you create a Stream from an array?
Use Arrays.stream(array).
int[] a = {4, 8, 12};
Arrays.stream(a).forEach(System.out::println);
Output
4
8
12
5. How do you filter even numbers?
filter() keeps only elements that satisfy the predicate.
List<Integer> result = List.of(1,2,3,4,5,6).stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(result);
Output
[2, 4, 6]
6. How do you convert all strings to uppercase?
Use map() to transform each element.
List<String> result = List.of("java","stream","api").stream()
.map(String::toUpperCase)
.toList();
System.out.println(result);
Output
[JAVA, STREAM, API]
7. How do you count Stream elements?
count() is a terminal operation that returns a long.
long count = Stream.of("A","B","C","D").count();
System.out.println(count);
Output
4
8. How do you find the first element?
findFirst() returns an Optional.
int value = Stream.of(10,20,30).findFirst().orElse(-1);
System.out.println(value);
Output
10
9. How do you check whether any element matches a predicate?
anyMatch() short-circuits when the first match is found.
boolean result = List.of(3,7,11,20).stream()
.anyMatch(n -> n > 15);
System.out.println(result);
Output
true
10. How do you check whether all elements match a predicate?
allMatch() returns true only if every element matches.
boolean result = List.of(2,4,6,8).stream()
.allMatch(n -> n % 2 == 0);
System.out.println(result);
Output
true
11. How do you check that no element matches?
Use noneMatch().
boolean result = List.of(1,3,5,7).stream()
.noneMatch(n -> n % 2 == 0);
System.out.println(result);
Output
true
12. How do you sort a Stream in natural order?
Use sorted().
System.out.println(List.of(9,2,6,1).stream().sorted().toList());
Output
[1, 2, 6, 9]
13. How do you sort in reverse order?
Pass Comparator.reverseOrder().
System.out.println(List.of(9,2,6,1).stream()
.sorted(Comparator.reverseOrder())
.toList());
Output
[9, 6, 2, 1]
14. How do you remove duplicates?
distinct() removes duplicates according to equality semantics.
System.out.println(Stream.of(1,2,2,3,3,3).distinct().toList());
Output
[1, 2, 3]
15. How do you take only the first three elements?
Use limit(3).
System.out.println(Stream.of(10,20,30,40,50).limit(3).toList());
Output
[10, 20, 30]
16. How do you skip the first two elements?
Use skip(2).
System.out.println(Stream.of(10,20,30,40).skip(2).toList());
Output
[30, 40]
17. How do you sum numbers with reduce()?
reduce(identity, accumulator) combines all elements into one result.
int sum = Stream.of(1,2,3,4).reduce(0, Integer::sum);
System.out.println(sum);
Output
10
18. How do you find the maximum element?
Use max() with a comparator.
int max = Stream.of(8,4,12,3).max(Integer::compareTo).orElse(-1);
System.out.println(max);
Output
12
19. How do you find the minimum element?
Use min() with a comparator.
int min = Stream.of(8,4,12,3).min(Integer::compareTo).orElse(-1);
System.out.println(min);
Output
3
20. How do you convert a Stream to a List?
Use toList() in modern Java.
List<String> list = Stream.of("A","B","C").toList();
System.out.println(list);
Output
[A, B, C]
21. How do you filter null values?
Use Objects::nonNull.
System.out.println(Stream.of("Java", null, "SQL", null)
.filter(Objects::nonNull)
.toList());
Output
[Java, SQL]
22. How do you remove empty strings?
Filter with !String::isEmpty logic.
System.out.println(Stream.of("Java","","Spring","")
.filter(s -> !s.isEmpty())
.toList());
Output
[Java, Spring]
23. How do you remove blank strings including spaces?
Use String.isBlank().
System.out.println(Stream.of("Java"," ","SQL","")
.filter(s -> !s.isBlank())
.toList());
Output
[Java, SQL]
24. How do you find strings longer than four characters?
Filter by length().
System.out.println(List.of("Java","Spring","SQL","Docker").stream()
.filter(s -> s.length() > 4)
.toList());
Output
[Spring, Docker]
25. How do you filter names beginning with A?
Use a predicate with startsWith().
System.out.println(List.of("Amit","Riya","Ankit","Neha").stream()
.filter(s -> s.startsWith("A"))
.toList());
Output
[Amit, Ankit]
26. How do you filter names ending with 'a'?
Use endsWith().
System.out.println(List.of("Riya","Amit","Neha","Kabir").stream()
.filter(s -> s.endsWith("a"))
.toList());
Output
[Riya, Neha]
27. How do you convert strings to their lengths?
Map each string with String::length.
System.out.println(List.of("Java","Spring","SQL").stream()
.map(String::length)
.toList());
Output
[4, 6, 3]
28. How do you square every integer?
Use map(n -> n*n).
System.out.println(List.of(1,2,3,4).stream()
.map(n -> n * n)
.toList());
Output
[1, 4, 9, 16]
29. How do you cube every integer?
Transform each value using map().
System.out.println(Stream.of(1,2,3,4)
.map(n -> n * n * n)
.toList());
Output
[1, 8, 27, 64]
30. How do you parse a Stream of numeric strings?
Map with Integer::parseInt.
System.out.println(Stream.of("10","20","30")
.map(Integer::parseInt)
.toList());
Output
[10, 20, 30]
31. How do you double only even numbers?
Filter first, then map.
System.out.println(List.of(1,2,3,4,5,6).stream()
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.toList());
Output
[4, 8, 12]
32. Can you chain two filters in a Stream?
Yes. Multiple filters are applied sequentially.
System.out.println(List.of(1,2,3,4,5,6,7,8,9,10).stream()
.filter(n -> n > 3)
.filter(n -> n % 2 == 0)
.toList());
Output
[4, 6, 8, 10]
Interview follow-up: This exact pattern is reported in Java interview experiences.
33. How do you trim every string?
Use map(String::trim).
System.out.println(Stream.of(" Java "," SQL ","Spring ")
.map(String::trim)
.toList());
Output
[Java, SQL, Spring]
34. How do you extract the first character of each non-empty string?
Filter empty strings and map with charAt(0).
System.out.println(Stream.of("Java","SQL","Go")
.map(s -> s.charAt(0))
.toList());
Output
[J, S, G]
35. How do you add a prefix to each element?
Use map().
System.out.println(Stream.of("101","102","103")
.map(id -> "EMP-" + id)
.toList());
Output
[EMP-101, EMP-102, EMP-103]
36. How do you convert negative numbers to absolute values?
Use Math::abs.
System.out.println(Stream.of(-4,2,-7,5)
.map(Math::abs)
.toList());
Output
[4, 2, 7, 5]
37. How do you select numbers in a range?
Use a compound predicate.
System.out.println(IntStream.rangeClosed(1, 12)
.boxed()
.filter(n -> n >= 5 && n <= 9)
.toList());
Output
[5, 6, 7, 8, 9]
38. How do you filter strings case-insensitively by prefix?
Normalize case inside the predicate.
System.out.println(Stream.of("Java","javascript","Python","JAVAFX")
.filter(s -> s.toLowerCase().startsWith("java"))
.toList());
Output
[Java, javascript, JAVAFX]
39. How do you transform every word to word:length?
Map each element to a formatted string.
System.out.println(Stream.of("Java","SQL","Spring")
.map(s -> s + ":" + s.length())
.toList());
Output
[Java:4, SQL:3, Spring:6]
40. How do you get only odd squares?
Filter odd numbers then square them.
System.out.println(Stream.of(1,2,3,4,5)
.filter(n -> n % 2 != 0)
.map(n -> n * n)
.toList());
Output
[1, 9, 25]
41. What is the difference between map() and flatMap()?
map() produces one result per input element. flatMap() flattens nested streams into one stream.
List<List<Integer>> data = List.of(List.of(1,2), List.of(3,4));
System.out.println(data.stream()
.flatMap(List::stream)
.toList());
Output
[1, 2, 3, 4]
Interview follow-up: map() vs flatMap() is a repeatedly reported Java 8 interview question.
42. How do you flatten a List<List<String>>?
Use flatMap(List::stream).
List<List<String>> groups = List.of(
List.of("Java","SQL"),
List.of("Spring","Docker")
);
System.out.println(groups.stream().flatMap(List::stream).toList());
Output
[Java, SQL, Spring, Docker]
43. How do you get unique words from multiple sentences?
Split each sentence, flatten the arrays, then call distinct().
List<String> sentences = List.of("java stream api", "java api interview");
System.out.println(sentences.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.distinct()
.toList());
Output
[java, stream, api, interview]
44. How do you get all characters from a list of words?
Convert each string to an IntStream, map to chars, and flatten.
List<Character> chars = List.of("ab","cd").stream()
.flatMap(s -> s.chars().mapToObj(c -> (char)c))
.toList();
System.out.println(chars);
Output
[a, b, c, d]
45. How do you split CSV values and flatten them?
Map each CSV row to an array stream and flatten.
System.out.println(Stream.of("Java,SQL", "Spring,Docker")
.flatMap(s -> Arrays.stream(s.split(",")))
.toList());
Output
[Java, SQL, Spring, Docker]
46. How do you find duplicate characters in a string using Streams?
Group characters by identity, count them, and keep counts greater than one.
Map<Character, Long> freq = "programming".chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
));
System.out.println(freq.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.toList());
Output
[r, g, m]
Interview follow-up: Finding duplicates using Streams is documented in interview reports.
47. How do you find the first non-repeating character?
Use a LinkedHashMap to preserve encounter order.
Map<Character, Long> freq = "swiss".chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
));
Character ch = freq.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
System.out.println(ch);
Output
w
Interview follow-up: Non-repeating-character Stream questions are reported in backend Java interviews.
48. How do you find the first repeating character?
Track counts in encounter order and select the first count greater than one.
Map<Character, Long> freq = "success".chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
));
System.out.println(freq.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null));
Output
s
49. How do you count each character in a string?
Group by character and use counting().
Map<Character, Long> map = "banana".chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(
Function.identity(),
TreeMap::new,
Collectors.counting()
));
System.out.println(map);
Output
{a=3, b=1, n=2}
50. How do you count each word in a sentence?
Split into words then group and count.
Map<String, Long> map = Arrays.stream("java sql java stream sql java".split(" "))
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
));
System.out.println(map);
Output
{java=3, sql=2, stream=1}
51. How do you find words that appear more than once?
Count words and filter entries with a count greater than one.
Map<String, Long> freq = Arrays.stream("a b a c b a".split(" "))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(freq.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.sorted()
.toList());
Output
[a, b]
52. How do you reverse each string in a list?
Map each string through StringBuilder.reverse().
System.out.println(Stream.of("Java","SQL","API")
.map(s -> new StringBuilder(s).reverse().toString())
.toList());
Output
[avaJ, LQS, IPA]
53. How do you keep only palindromes?
Compare each string with its reversed form.
System.out.println(Stream.of("level","java","madam","stream")
.filter(s -> s.equals(new StringBuilder(s).reverse().toString()))
.toList());
Output
[level, madam]
54. How do you sort strings by length?
Use Comparator.comparingInt(String::length).
System.out.println(Stream.of("Spring","Go","Java","SQL")
.sorted(Comparator.comparingInt(String::length))
.toList());
Output
[Go, SQL, Java, Spring]
55. How do you sort strings by length descending?
Reverse the length comparator.
System.out.println(Stream.of("Spring","Go","Java","SQL")
.sorted(Comparator.comparingInt(String::length).reversed())
.toList());
Output
[Spring, Java, SQL, Go]
56. How do you find the longest string?
Use max(Comparator.comparingInt(String::length)).
String longest = Stream.of("Java","Microservices","SQL","Spring")
.max(Comparator.comparingInt(String::length))
.orElse("");
System.out.println(longest);
Output
Microservices
57. How do you find the shortest string?
Use min() with a length comparator.
String shortest = Stream.of("Java","Go","Spring","SQL")
.min(Comparator.comparingInt(String::length))
.orElse("");
System.out.println(shortest);
Output
Go
58. How do you concatenate characters of a string with hyphens?
Turn characters into strings and join them.
String result = "JAVA".chars()
.mapToObj(c -> String.valueOf((char)c))
.collect(Collectors.joining("-"));
System.out.println(result);
Output
J-A-V-A
59. How do you find vowels in a string?
Filter character stream against a vowel set.
List<Character> vowels = "interview".chars()
.mapToObj(c -> (char)c)
.filter(c -> "aeiouAEIOU".indexOf(c) >= 0)
.toList();
System.out.println(vowels);
Output
[i, e, i, e]
60. How do you count vowels using Streams?
Filter the character stream then count.
long count = "microservices".chars()
.mapToObj(c -> (char)c)
.filter(c -> "aeiou".indexOf(c) >= 0)
.count();
System.out.println(count);
Output
5
61. How do you find the second-highest distinct number?
Remove duplicates, sort descending, skip one, and take the first.
int value = Stream.of(10,30,20,30,40,40)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElse(-1);
System.out.println(value);
Output
30
62. How do you find the third-highest distinct number?
Sort distinct values in reverse and skip two.
int value = Stream.of(5,9,7,9,10,8)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(2)
.findFirst()
.orElse(-1);
System.out.println(value);
Output
8
63. How do you get the top three largest distinct numbers?
Combine distinct(), descending sort, and limit(3).
System.out.println(Stream.of(4,10,8,10,2,9,8)
.distinct()
.sorted(Comparator.reverseOrder())
.limit(3)
.toList());
Output
[10, 9, 8]
64. How do you get the bottom three numbers?
Sort naturally and limit.
System.out.println(Stream.of(9,4,7,1,3,6)
.sorted()
.limit(3)
.toList());
Output
[1, 3, 4]
65. How do you sort strings alphabetically ignoring case?
Use String.CASE_INSENSITIVE_ORDER.
System.out.println(Stream.of("spring","Java","api","Docker")
.sorted(String.CASE_INSENSITIVE_ORDER)
.toList());
Output
[api, Docker, Java, spring]
66. How do you sort employees by salary ascending?
Use a comparator on the salary field.
record Employee(String name, int salary) {}
List<Employee> employees = List.of(
new Employee("A", 70000),
new Employee("B", 50000),
new Employee("C", 90000)
);
System.out.println(employees.stream()
.sorted(Comparator.comparingInt(Employee::salary))
.map(Employee::name)
.toList());
Output
[B, A, C]
67. How do you sort employees by salary descending?
Reverse the salary comparator.
record Employee(String name, int salary) {}
List<Employee> employees = List.of(
new Employee("A", 70000),
new Employee("B", 50000),
new Employee("C", 90000)
);
System.out.println(employees.stream()
.sorted(Comparator.comparingInt(Employee::salary).reversed())
.map(Employee::name)
.toList());
Output
[C, A, B]
68. How do you sort by salary and then by name?
Chain comparators using thenComparing().
record Employee(String name, int salary) {}
List<Employee> employees = List.of(
new Employee("Riya", 70000),
new Employee("Amit", 70000),
new Employee("Kabir", 60000)
);
System.out.println(employees.stream()
.sorted(Comparator.comparingInt(Employee::salary)
.thenComparing(Employee::name))
.map(Employee::name)
.toList());
Output
[Kabir, Amit, Riya]
69. How do you sort map entries by value?
Stream over entrySet() and sort by value.
Map<String,Integer> m = Map.of("A",3,"B",1,"C",2);
System.out.println(m.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.map(e -> e.getKey() + "=" + e.getValue())
.toList());
Output
[B=1, C=2, A=3]
70. How do you sort map entries by value descending?
Reverse Map.Entry.comparingByValue().
Map<String,Integer> m = Map.of("A",3,"B",1,"C",2);
System.out.println(m.entrySet().stream()
.sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
.map(e -> e.getKey() + "=" + e.getValue())
.toList());
Output
[A=3, C=2, B=1]
71. How do you remove duplicate strings ignoring case?
Normalize to lowercase before distinct().
System.out.println(Stream.of("Java","JAVA","Spring","spring","SQL")
.map(String::toLowerCase)
.distinct()
.toList());
Output
[java, spring, sql]
72. How do you retain encounter order while removing duplicates?
distinct() preserves encounter order for ordered streams.
System.out.println(Stream.of(3,1,2,3,1,4).distinct().toList());
Output
[3, 1, 2, 4]
73. How do you find duplicate integers?
Group and count, then keep counts above one.
Map<Integer,Long> freq = Stream.of(1,2,2,3,4,4,4)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(freq.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.sorted()
.toList());
Output
[2, 4]
74. How do you find unique elements that occur exactly once?
Count frequencies and keep count 1.
Map<Integer,Long> freq = Stream.of(1,2,2,3,4,4,5)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(freq.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.sorted()
.toList());
Output
[1, 3, 5]
75. How do you find the most frequent number?
Count frequencies and select the maximum count.
Map<Integer,Long> freq = Stream.of(2,3,3,4,4,4,5)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(freq.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null));
Output
4
76. How do you find the least frequent number?
Count and choose the minimum frequency.
Map<Integer,Long> freq = Stream.of(1,1,2,2,2,3)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(freq.entrySet().stream()
.min(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null));
Output
3
77. How do you get the five highest values from 1 to 20?
Sort descending and limit.
System.out.println(IntStream.rangeClosed(1,20)
.boxed()
.sorted(Comparator.reverseOrder())
.limit(5)
.toList());
Output
[20, 19, 18, 17, 16]
78. How do you select every third value from an ordered range?
Filter based on divisibility.
System.out.println(IntStream.rangeClosed(1,15)
.filter(n -> n % 3 == 0)
.boxed()
.toList());
Output
[3, 6, 9, 12, 15]
79. How do you find the first value greater than 100 after sorting?
Sort then filter and find first.
System.out.println(Stream.of(150,50,120,80,110)
.sorted()
.filter(n -> n > 100)
.findFirst()
.orElse(-1));
Output
110
80. How do you find the largest three even numbers?
Filter evens, sort descending, then limit.
System.out.println(Stream.of(3,12,8,15,20,6,18)
.filter(n -> n % 2 == 0)
.sorted(Comparator.reverseOrder())
.limit(3)
.toList());
Output
[20, 18, 12]
81. How do you sum integers with mapToInt()?
Primitive streams provide numeric terminal operations.
int sum = Stream.of(10,20,30).mapToInt(Integer::intValue).sum();
System.out.println(sum);
Output
60
82. How do you calculate an average?
average() returns OptionalDouble.
double avg = Stream.of(10,20,30,40)
.mapToInt(Integer::intValue)
.average()
.orElse(0);
System.out.println(avg);
Output
25.0
83. How do you calculate the product using reduce()?
Use identity 1 and multiply.
int product = Stream.of(2,3,4).reduce(1, (a,b) -> a * b);
System.out.println(product);
Output
24
84. How do you concatenate strings using reduce()?
Reduce strings into one string.
String value = Stream.of("Java","Stream","API")
.reduce("", (a,b) -> a + b);
System.out.println(value);
Output
JavaStreamAPI
85. How do you find the sum of squares?
Map to squared values then sum.
int sum = IntStream.rangeClosed(1,4)
.map(n -> n * n)
.sum();
System.out.println(sum);
Output
30
86. How do you sum only even values?
Filter the primitive stream first.
int sum = IntStream.rangeClosed(1,10)
.filter(n -> n % 2 == 0)
.sum();
System.out.println(sum);
Output
30
87. How do you sum only odd values?
Filter odds then sum.
int sum = IntStream.rangeClosed(1,10)
.filter(n -> n % 2 != 0)
.sum();
System.out.println(sum);
Output
25
88. How do you calculate factorial with Streams?
Use rangeClosed and reduce.
int factorial = IntStream.rangeClosed(1,5)
.reduce(1, (a,b) -> a * b);
System.out.println(factorial);
Output
120
89. How do you generate the first six even numbers?
Use iterate() or a mapped range.
System.out.println(Stream.iterate(2, n -> n + 2)
.limit(6)
.toList());
Output
[2, 4, 6, 8, 10, 12]
90. How do you generate powers of two?
Use Stream.iterate() with multiplication.
System.out.println(Stream.iterate(1, n -> n * 2)
.limit(6)
.toList());
Output
[1, 2, 4, 8, 16, 32]
91. How do you get IntSummaryStatistics?
summaryStatistics() provides count, sum, min, average, and max.
IntSummaryStatistics s = IntStream.of(10,20,30,40).summaryStatistics();
System.out.println(s.getCount());
System.out.println(s.getSum());
System.out.println(s.getMin());
System.out.println(s.getMax());
Output
4
100
10
40
92. How do you calculate average salary?
Map salaries to a primitive stream.
record Employee(String name, int salary) {}
List<Employee> e = List.of(new Employee("A",50000), new Employee("B",70000));
double avg = e.stream().mapToInt(Employee::salary).average().orElse(0);
System.out.println(avg);
Output
60000.0
93. How do you find total salary?
Use mapToInt().sum().
record Employee(String name, int salary) {}
List<Employee> e = List.of(new Employee("A",50000), new Employee("B",70000));
System.out.println(e.stream().mapToInt(Employee::salary).sum());
Output
120000
94. How do you find maximum salary?
Use mapToInt().max().
record Employee(String name, int salary) {}
List<Employee> e = List.of(new Employee("A",50000), new Employee("B",70000));
System.out.println(e.stream().mapToInt(Employee::salary).max().orElse(0));
Output
70000
95. How do you find minimum salary?
Use mapToInt().min().
record Employee(String name, int salary) {}
List<Employee> e = List.of(new Employee("A",50000), new Employee("B",70000));
System.out.println(e.stream().mapToInt(Employee::salary).min().orElse(0));
Output
50000
96. How do you count numbers greater than the average?
Compute the average first, then filter.
List<Integer> nums = List.of(10,20,30,40,50);
double avg = nums.stream().mapToInt(Integer::intValue).average().orElse(0);
long count = nums.stream().filter(n -> n > avg).count();
System.out.println(avg);
System.out.println(count);
Output
30.0
2
97. How do you find employees earning above average salary?
Calculate average salary and filter employees above it.
record Employee(String name, int salary) {}
List<Employee> e = List.of(
new Employee("A",50000),
new Employee("B",70000),
new Employee("C",90000)
);
double avg = e.stream().mapToInt(Employee::salary).average().orElse(0);
System.out.println(e.stream()
.filter(x -> x.salary() > avg)
.map(Employee::name)
.toList());
Output
[C]
Interview follow-up: This type of above-average salary Stream problem is reported in Java interviews.
98. How do you calculate the sum of digits with Streams?
Convert the number to a string, stream characters, convert digits, then sum.
int sum = String.valueOf(5832).chars()
.map(c -> c - '0')
.sum();
System.out.println(sum);
Output
18
99. How do you find the largest digit in a number?
Stream over its characters and convert to digits.
int max = String.valueOf(583294).chars()
.map(c -> c - '0')
.max()
.orElse(-1);
System.out.println(max);
Output
9
100. How do you calculate the sum from 1 to 100?
Use a primitive range.
System.out.println(IntStream.rangeClosed(1,100).sum());
Output
5050
101. How do you collect a Stream to a Set?
Use Collectors.toSet().
Set<Integer> s = Stream.of(1,2,2,3).collect(Collectors.toSet());
System.out.println(new TreeSet<>(s));
Output
[1, 2, 3]
102. How do you collect into a specific ArrayList implementation?
Use Collectors.toCollection().
ArrayList<String> list = Stream.of("A","B")
.collect(Collectors.toCollection(ArrayList::new));
list.add("C");
System.out.println(list);
Output
[A, B, C]
103. How do you join strings with commas?
Use Collectors.joining(delimiter).
String s = Stream.of("Java","SQL","Spring")
.collect(Collectors.joining(", "));
System.out.println(s);
Output
Java, SQL, Spring
104. How do you join with prefix and suffix?
Use the three-argument joining().
String s = Stream.of("A","B","C")
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(s);
Output
[A, B, C]
105. How do you convert a list to a Map keyed by name?
Use Collectors.toMap().
record Employee(int id, String name) {}
List<Employee> e = List.of(new Employee(1,"A"),new Employee(2,"B"));
Map<String,Integer> map = e.stream()
.collect(Collectors.toMap(Employee::name, Employee::id));
System.out.println(new TreeMap<>(map));
Output
{A=1, B=2}
106. How do you handle duplicate keys in Collectors.toMap()?
Supply a merge function.
Map<String,Integer> map = Stream.of("Java","Java","SQL")
.collect(Collectors.toMap(
Function.identity(),
s -> 1,
Integer::sum
));
System.out.println(new TreeMap<>(map));
Output
{Java=2, SQL=1}
107. How do you create a LinkedHashMap with toMap()?
Provide a map supplier.
Map<String,Integer> map = Stream.of("C","A","B")
.collect(Collectors.toMap(
Function.identity(),
String::length,
(a,b) -> a,
LinkedHashMap::new
));
System.out.println(map);
Output
{C=1, A=1, B=1}
108. How do you count elements with Collectors.counting()?
Use it as a collector.
long count = Stream.of("A","B","C")
.collect(Collectors.counting());
System.out.println(count);
Output
3
109. How do you sum values with Collectors.summingInt()?
Map each object to an int inside the collector.
record Item(String name, int price) {}
List<Item> items = List.of(new Item("A",10), new Item("B",25));
int total = items.stream().collect(Collectors.summingInt(Item::price));
System.out.println(total);
Output
35
110. How do you average with Collectors.averagingInt()?
Use an averaging collector.
double avg = Stream.of(10,20,30)
.collect(Collectors.averagingInt(Integer::intValue));
System.out.println(avg);
Output
20.0
111. How do you get statistics with summarizingInt()?
Use Collectors.summarizingInt().
IntSummaryStatistics s = Stream.of(5,10,15)
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println(s.getSum() + "," + s.getAverage());
Output
30,10.0
112. How do you collect mapped values directly?
Use Collectors.mapping() as a downstream collector.
record Employee(String dept, String name) {}
List<Employee> e = List.of(new Employee("IT","A"), new Employee("HR","B"));
List<String> names = e.stream()
.collect(Collectors.mapping(Employee::name, Collectors.toList()));
System.out.println(names);
Output
[A, B]
113. How do you collect only filtered values with filtering()?
Java 9+ provides Collectors.filtering().
List<Integer> result = Stream.of(1,2,3,4,5)
.collect(Collectors.filtering(n -> n % 2 == 0, Collectors.toList()));
System.out.println(result);
Output
[2, 4]
114. How do you flatten nested collections using flatMapping collector?
Use Collectors.flatMapping().
record Team(String name, List<String> skills) {}
List<Team> teams = List.of(
new Team("A", List.of("Java","SQL")),
new Team("B", List.of("Docker","AWS"))
);
List<String> skills = teams.stream()
.collect(Collectors.flatMapping(
t -> t.skills().stream(),
Collectors.toList()
));
System.out.println(skills);
Output
[Java, SQL, Docker, AWS]
115. How do you transform the final collected result?
Use collectingAndThen().
int size = Stream.of("A","B","C")
.collect(Collectors.collectingAndThen(
Collectors.toList(),
List::size
));
System.out.println(size);
Output
3
116. How do you create an unmodifiable list after collecting?
Use Collectors.toUnmodifiableList().
List<String> list = Stream.of("A","B","C")
.collect(Collectors.toUnmodifiableList());
System.out.println(list);
Output
[A, B, C]
117. How do you create an unmodifiable Set?
Use Collectors.toUnmodifiableSet().
Set<Integer> set = Stream.of(1,2,2,3)
.collect(Collectors.toUnmodifiableSet());
System.out.println(new TreeSet<>(set));
Output
[1, 2, 3]
118. How do you find the maximum using Collectors.maxBy()?
maxBy() returns an Optional.
int max = Stream.of(5,9,3)
.collect(Collectors.maxBy(Integer::compareTo))
.orElse(-1);
System.out.println(max);
Output
9
119. How do you find the minimum using Collectors.minBy()?
Use Collectors.minBy().
int min = Stream.of(5,9,3)
.collect(Collectors.minBy(Integer::compareTo))
.orElse(-1);
System.out.println(min);
Output
3
120. How do you reduce with Collectors.reducing()?
reducing() provides reduction in collector form.
int sum = Stream.of(1,2,3,4)
.collect(Collectors.reducing(0, Integer::sum));
System.out.println(sum);
Output
10
121. How do you group employees by department?
Use groupingBy().
record Employee(String name, String dept) {}
List<Employee> e = List.of(
new Employee("A","IT"),
new Employee("B","HR"),
new Employee("C","IT")
);
Map<String,List<String>> map = e.stream()
.collect(Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.mapping(Employee::name, Collectors.toList())
));
System.out.println(map);
Output
{HR=[B], IT=[A, C]}
122. How do you count employees in each department?
Use groupingBy() with counting().
record Employee(String name,String dept) {}
List<Employee> e = List.of(
new Employee("A","IT"), new Employee("B","HR"),
new Employee("C","IT"), new Employee("D","IT")
);
Map<String,Long> map = e.stream()
.collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.counting()));
System.out.println(map);
Output
{HR=1, IT=3}
123. How do you calculate total salary by department?
Use summingInt() downstream.
record Employee(String dept,int salary) {}
List<Employee> e = List.of(
new Employee("IT",60000), new Employee("IT",80000),
new Employee("HR",50000)
);
Map<String,Integer> map = e.stream()
.collect(Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.summingInt(Employee::salary)
));
System.out.println(map);
Output
{HR=50000, IT=140000}
124. How do you calculate average salary by department?
Use averagingInt() downstream.
record Employee(String dept,int salary) {}
List<Employee> e = List.of(
new Employee("IT",60000), new Employee("IT",80000),
new Employee("HR",50000)
);
Map<String,Double> map = e.stream()
.collect(Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.averagingInt(Employee::salary)
));
System.out.println(map);
Output
{HR=50000.0, IT=70000.0}
125. How do you find the highest-paid employee in each department?
Group by department and use maxBy().
record Employee(String name,String dept,int salary) {}
List<Employee> e = List.of(
new Employee("A","IT",70000),
new Employee("B","IT",90000),
new Employee("C","HR",60000)
);
Map<String,String> result = e.stream().collect(
Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingInt(Employee::salary)),
x -> x.map(Employee::name).orElse("")
)
)
);
System.out.println(result);
Output
{HR=C, IT=B}
Interview follow-up: Highest salary per department is explicitly reported in Java interview experiences.
126. How do you find the lowest-paid employee in each department?
Use minBy() downstream.
record Employee(String name,String dept,int salary) {}
List<Employee> e = List.of(
new Employee("A","IT",70000),
new Employee("B","IT",90000),
new Employee("C","HR",60000)
);
Map<String,String> result = e.stream().collect(
Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.collectingAndThen(
Collectors.minBy(Comparator.comparingInt(Employee::salary)),
x -> x.map(Employee::name).orElse("")
)
)
);
System.out.println(result);
Output
{HR=C, IT=A}
127. How do you group strings by length?
Use the string length as classification key.
Map<Integer,List<String>> map = Stream.of("Go","Java","SQL","Spring")
.collect(Collectors.groupingBy(
String::length,
TreeMap::new,
Collectors.toList()
));
System.out.println(map);
Output
{2=[Go], 3=[SQL], 4=[Java], 6=[Spring]}
128. How do you group numbers into even and odd?
Use partitioningBy() for a boolean split.
Map<Boolean,List<Integer>> map = IntStream.rangeClosed(1,6)
.boxed()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(map);
Output
{false=[1, 3, 5], true=[2, 4, 6]}
129. How do you partition employees by salary threshold?
Use partitioningBy(e -> salary >= threshold).
record Employee(String name,int salary) {}
List<Employee> e = List.of(
new Employee("A",50000),
new Employee("B",80000),
new Employee("C",90000)
);
Map<Boolean,List<String>> result = e.stream().collect(
Collectors.partitioningBy(
x -> x.salary() >= 80000,
Collectors.mapping(Employee::name, Collectors.toList())
)
);
System.out.println(result);
Output
{false=[A], true=[B, C]}
130. How do you count even and odd numbers with partitioningBy()?
Use counting() downstream.
Map<Boolean,Long> map = IntStream.rangeClosed(1,10)
.boxed()
.collect(Collectors.partitioningBy(n -> n % 2 == 0, Collectors.counting()));
System.out.println(map);
Output
{false=5, true=5}
131. How do you group words by first character?
Use the first character as the classifier.
Map<Character,List<String>> map = Stream.of("Java","Job","Spring","SQL")
.collect(Collectors.groupingBy(
s -> s.charAt(0),
TreeMap::new,
Collectors.toList()
));
System.out.println(map);
Output
{J=[Java, Job], S=[Spring, SQL]}
132. How do you group words by first character and count them?
Combine grouping with counting.
Map<Character,Long> map = Stream.of("Java","Job","Spring","SQL","JPA")
.collect(Collectors.groupingBy(
s -> s.charAt(0),
TreeMap::new,
Collectors.counting()
));
System.out.println(map);
Output
{J=3, S=2}
133. How do you group employees by department and extract only names?
Use mapping() downstream.
record Employee(String name,String dept) {}
List<Employee> e = List.of(
new Employee("A","IT"),new Employee("B","HR"),new Employee("C","IT")
);
Map<String,List<String>> map = e.stream().collect(
Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.mapping(Employee::name, Collectors.toList())
)
);
System.out.println(map);
Output
{HR=[B], IT=[A, C]}
134. How do you group employees by department and collect unique skills?
Use grouping plus flatMapping() into a Set.
record Employee(String dept,List<String> skills) {}
List<Employee> e = List.of(
new Employee("IT",List.of("Java","SQL")),
new Employee("IT",List.of("Java","AWS")),
new Employee("HR",List.of("Excel"))
);
Map<String,Set<String>> map = e.stream().collect(
Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.flatMapping(x -> x.skills().stream(), Collectors.toCollection(TreeSet::new))
)
);
System.out.println(map);
Output
{HR=[Excel], IT=[AWS, Java, SQL]}
135. How do you perform nested grouping by department and gender?
Call groupingBy() as a downstream collector.
record Employee(String dept,String gender,String name) {}
List<Employee> e = List.of(
new Employee("IT","M","A"),
new Employee("IT","F","B"),
new Employee("IT","M","C"),
new Employee("HR","F","D")
);
Map<String,Map<String,Long>> map = e.stream().collect(
Collectors.groupingBy(
Employee::dept,
TreeMap::new,
Collectors.groupingBy(Employee::gender, TreeMap::new, Collectors.counting())
)
);
System.out.println(map);
Output
{HR={F=1}, IT={F=1, M=2}}
136. How do you group integers by remainder modulo 3?
Use n -> n % 3 as classifier.
Map<Integer,List<Integer>> map = IntStream.rangeClosed(1,7)
.boxed()
.collect(Collectors.groupingBy(n -> n % 3, TreeMap::new, Collectors.toList()));
System.out.println(map);
Output
{0=[3, 6], 1=[1, 4, 7], 2=[2, 5]}
137. How do you group transactions by type and sum amounts?
Group then use summingInt().
record Tx(String type,int amount) {}
List<Tx> tx = List.of(
new Tx("CREDIT",100),new Tx("DEBIT",40),new Tx("CREDIT",60)
);
Map<String,Integer> map = tx.stream().collect(
Collectors.groupingBy(Tx::type, TreeMap::new, Collectors.summingInt(Tx::amount))
);
System.out.println(map);
Output
{CREDIT=160, DEBIT=40}
138. How do you partition strings into blank and non-blank?
Use partitioningBy(String::isBlank).
Map<Boolean,List<String>> map = Stream.of("Java"," ","SQL","")
.collect(Collectors.partitioningBy(String::isBlank));
System.out.println(map);
Output
{false=[Java, SQL], true=[ , ]}
139. How do you group numbers by digit count?
Convert to string and classify by length.
Map<Integer,List<Integer>> map = Stream.of(7,42,105,8,999)
.collect(Collectors.groupingBy(
n -> String.valueOf(n).length(),
TreeMap::new,
Collectors.toList()
));
System.out.println(map);
Output
{1=[7, 8], 2=[42], 3=[105, 999]}
140. How do you find department salary statistics?
Use summarizingInt() downstream.
record Employee(String dept,int salary) {}
List<Employee> e = List.of(
new Employee("IT",60000),new Employee("IT",80000),new Employee("HR",50000)
);
Map<String,IntSummaryStatistics> map = e.stream().collect(
Collectors.groupingBy(Employee::dept, TreeMap::new,
Collectors.summarizingInt(Employee::salary))
);
System.out.println(map.get("IT").getCount());
System.out.println(map.get("IT").getAverage());
Output
2
70000.0
141. How do you get employee names beginning with 'Su'?
Filter by prefix then map to names.
record Employee(String name) {}
List<Employee> e = List.of(
new Employee("Suman"),new Employee("Amit"),new Employee("Suresh")
);
System.out.println(e.stream()
.map(Employee::name)
.filter(n -> n.startsWith("Su"))
.toList());
Output
[Suman, Suresh]
Interview follow-up: A TCS Java interview report specifically describes this Stream problem.
142. How do you find the highest-paid employee?
Use max() with a salary comparator.
record Employee(String name,int salary) {}
List<Employee> e = List.of(
new Employee("A",60000),new Employee("B",90000),new Employee("C",75000)
);
System.out.println(e.stream()
.max(Comparator.comparingInt(Employee::salary))
.map(Employee::name)
.orElse(""));
Output
B
143. How do you find the second-highest-paid employee?
Sort by salary descending, skip one, and take first.
record Employee(String name,int salary) {}
List<Employee> e = List.of(
new Employee("A",60000),new Employee("B",90000),new Employee("C",75000)
);
System.out.println(e.stream()
.sorted(Comparator.comparingInt(Employee::salary).reversed())
.skip(1)
.findFirst()
.map(Employee::name)
.orElse(""));
Output
C
144. How do you get employees with salary above 70,000?
Filter by salary.
record Employee(String name,int salary) {}
List<Employee> e = List.of(
new Employee("A",60000),new Employee("B",90000),new Employee("C",75000)
);
System.out.println(e.stream()
.filter(x -> x.salary() > 70000)
.map(Employee::name)
.toList());
Output
[B, C]
145. How do you get active users sorted by name?
Filter by status, then sort.
record User(String name,boolean active) {}
List<User> users = List.of(
new User("Riya",true),new User("Amit",true),new User("Kabir",false)
);
System.out.println(users.stream()
.filter(User::active)
.map(User::name)
.sorted()
.toList());
Output
[Amit, Riya]
146. How do you find the most expensive product?
Use max() on price.
record Product(String name,int price) {}
List<Product> p = List.of(
new Product("Mouse",500),new Product("Keyboard",1500),new Product("Monitor",12000)
);
System.out.println(p.stream()
.max(Comparator.comparingInt(Product::price))
.map(Product::name)
.orElse(""));
Output
Monitor
147. How do you calculate cart total?
Map prices to ints and sum.
record Item(String name,int price) {}
List<Item> cart = List.of(new Item("A",100),new Item("B",250),new Item("C",50));
System.out.println(cart.stream().mapToInt(Item::price).sum());
Output
400
148. How do you find products priced between 500 and 2000?
Use a range predicate.
record Product(String name,int price) {}
List<Product> p = List.of(
new Product("A",300),new Product("B",800),new Product("C",1800),new Product("D",3000)
);
System.out.println(p.stream()
.filter(x -> x.price() >= 500 && x.price() <= 2000)
.map(Product::name)
.toList());
Output
[B, C]
149. How do you find orders above a threshold and sort by value?
Filter and sort descending.
record Order(String id,int total) {}
List<Order> orders = List.of(
new Order("O1",500),new Order("O2",2000),new Order("O3",1500)
);
System.out.println(orders.stream()
.filter(o -> o.total() >= 1000)
.sorted(Comparator.comparingInt(Order::total).reversed())
.map(Order::id)
.toList());
Output
[O2, O3]
150. How do you count users by city?
Group by city and count.
record User(String name,String city) {}
List<User> users = List.of(
new User("A","Delhi"),new User("B","Pune"),new User("C","Delhi")
);
System.out.println(users.stream().collect(
Collectors.groupingBy(User::city, TreeMap::new, Collectors.counting())
));
Output
{Delhi=2, Pune=1}
151. How do you find the oldest person?
Use max() by age.
record Person(String name,int age) {}
List<Person> p = List.of(new Person("A",25),new Person("B",42),new Person("C",31));
System.out.println(p.stream()
.max(Comparator.comparingInt(Person::age))
.map(Person::name)
.orElse(""));
Output
B
152. How do you find the youngest person in each city?
Group by city and use minBy().
record Person(String name,String city,int age) {}
List<Person> p = List.of(
new Person("A","Delhi",30),new Person("B","Delhi",24),
new Person("C","Pune",28)
);
Map<String,String> map = p.stream().collect(
Collectors.groupingBy(
Person::city,
TreeMap::new,
Collectors.collectingAndThen(
Collectors.minBy(Comparator.comparingInt(Person::age)),
x -> x.map(Person::name).orElse("")
)
)
);
System.out.println(map);
Output
{Delhi=B, Pune=C}
153. How do you get all unique technologies across employees?
Flatten skill lists and collect distinct values.
record Employee(String name,List<String> skills) {}
List<Employee> e = List.of(
new Employee("A",List.of("Java","SQL")),
new Employee("B",List.of("Java","AWS"))
);
System.out.println(e.stream()
.flatMap(x -> x.skills().stream())
.distinct()
.sorted()
.toList());
Output
[AWS, Java, SQL]
154. How do you find employees who know both Java and SQL?
Filter using two collection membership checks.
record Employee(String name,List<String> skills) {}
List<Employee> e = List.of(
new Employee("A",List.of("Java","SQL")),
new Employee("B",List.of("Java","AWS")),
new Employee("C",List.of("SQL","Java","Docker"))
);
System.out.println(e.stream()
.filter(x -> x.skills().contains("Java") && x.skills().contains("SQL"))
.map(Employee::name)
.toList());
Output
[A, C]
155. How do you select the latest transaction?
Use max() by timestamp-like sequence.
record Tx(String id,long time) {}
List<Tx> tx = List.of(new Tx("T1",100),new Tx("T2",300),new Tx("T3",200));
System.out.println(tx.stream()
.max(Comparator.comparingLong(Tx::time))
.map(Tx::id)
.orElse(""));
Output
T2
156. How do you find customers with more than two orders?
Group by customer and filter counts.
record Order(String customer) {}
List<Order> o = List.of(
new Order("A"),new Order("A"),new Order("A"),
new Order("B"),new Order("B")
);
Map<String,Long> c = o.stream().collect(
Collectors.groupingBy(Order::customer, Collectors.counting())
);
System.out.println(c.entrySet().stream()
.filter(e -> e.getValue() > 2)
.map(Map.Entry::getKey)
.toList());
Output
[A]
157. How do you get the top two products by sales?
Sort descending by sales and limit.
record Product(String name,int sales) {}
List<Product> p = List.of(
new Product("A",50),new Product("B",90),new Product("C",70)
);
System.out.println(p.stream()
.sorted(Comparator.comparingInt(Product::sales).reversed())
.limit(2)
.map(Product::name)
.toList());
Output
[B, C]
158. How do you find duplicate email addresses?
Group by email, count, and filter.
List<String> emails = List.of("a@x.com","b@x.com","a@x.com","c@x.com");
Map<String,Long> f = emails.stream().collect(
Collectors.groupingBy(Function.identity(), Collectors.counting())
);
System.out.println(f.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.toList());
Output
[a@x.com]
159. How do you sum invoice totals by customer?
Group by customer with a numeric downstream collector.
record Invoice(String customer,int amount) {}
List<Invoice> inv = List.of(
new Invoice("A",100),new Invoice("B",200),new Invoice("A",150)
);
System.out.println(inv.stream().collect(
Collectors.groupingBy(
Invoice::customer,
TreeMap::new,
Collectors.summingInt(Invoice::amount)
)
));
Output
{A=250, B=200}
160. How do you find the department with the highest total salary?
First aggregate salary by department, then find the max entry.
record Employee(String dept,int salary) {}
List<Employee> e = List.of(
new Employee("IT",80000),new Employee("IT",70000),
new Employee("HR",60000),new Employee("HR",50000)
);
Map<String,Integer> totals = e.stream().collect(
Collectors.groupingBy(Employee::dept, Collectors.summingInt(Employee::salary))
);
System.out.println(totals.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(""));
Output
IT
161. What happens if findFirst() is called on an empty Stream?
It returns Optional.empty().
Optional<Integer> x = Stream.<Integer>empty().findFirst();
System.out.println(x);
Output
Optional.empty
162. How do you provide a default value from an empty Stream?
Use orElse() on the Optional.
int x = Stream.<Integer>empty().findFirst().orElse(99);
System.out.println(x);
Output
99
163. How do you throw when no result is found?
Use orElseThrow().
try {
Stream.<String>empty().findFirst()
.orElseThrow(() -> new IllegalStateException("Not found"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
Output
Not found
164. What is the difference between IntStream.range() and rangeClosed()?
range() excludes the end; rangeClosed() includes it.
System.out.println(IntStream.range(1,4).boxed().toList());
System.out.println(IntStream.rangeClosed(1,4).boxed().toList());
Output
[1, 2, 3]
[1, 2, 3, 4]
165. How do you box an IntStream?
Call boxed().
List<Integer> list = IntStream.rangeClosed(1,3).boxed().toList();
System.out.println(list);
Output
[1, 2, 3]
166. How do you unbox a Stream<Integer> to IntStream?
Use mapToInt(Integer::intValue).
int sum = Stream.of(1,2,3).mapToInt(Integer::intValue).sum();
System.out.println(sum);
Output
6
167. How do you create an infinite Stream with generate()?
generate() repeats values from a supplier; limit it before collecting.
System.out.println(Stream.generate(() -> "X").limit(4).toList());
Output
[X, X, X, X]
168. How do you create an infinite arithmetic sequence?
Use Stream.iterate() and limit().
System.out.println(Stream.iterate(5, n -> n + 5)
.limit(5)
.toList());
Output
[5, 10, 15, 20, 25]
169. Are intermediate Stream operations lazy?
Yes. They run only when a terminal operation consumes the stream.
Stream<Integer> s = Stream.of(1,2,3)
.map(n -> {
System.out.println("map " + n);
return n * 2;
});
System.out.println("before terminal");
System.out.println(s.toList());
Output
before terminal
map 1
map 2
map 3
[2, 4, 6]
170. Why can anyMatch() process fewer elements than the whole Stream?
It is short-circuiting and stops once the answer is known.
boolean result = Stream.of(1,2,7,9)
.peek(n -> System.out.println("seen " + n))
.anyMatch(n -> n > 5);
System.out.println(result);
Output
seen 1
seen 2
seen 7
true
171. Why can findFirst() short-circuit?
It only needs the first element of an ordered stream.
int x = Stream.of(10,20,30)
.peek(n -> System.out.println("seen " + n))
.findFirst()
.orElse(-1);
System.out.println(x);
Output
seen 10
10
172. Can a Stream be reused after a terminal operation?
No. A consumed Stream cannot be operated on again.
Stream<Integer> s = Stream.of(1,2,3);
System.out.println(s.count());
try {
System.out.println(s.count());
} catch (IllegalStateException e) {
System.out.println("stream already used");
}
Output
3
stream already used
173. Does peek() execute without a terminal operation?
No. It is an intermediate operation.
Stream<Integer> s = Stream.of(1,2,3)
.peek(System.out::println);
System.out.println("done");
Output
done
174. How do you use peek() to debug a pipeline?
Place it between stages to observe elements.
List<Integer> r = Stream.of(1,2,3,4)
.filter(n -> n % 2 == 0)
.peek(n -> System.out.println("after filter " + n))
.map(n -> n * 10)
.toList();
System.out.println(r);
Output
after filter 2
after filter 4
[20, 40]
175. What happens when limit() is placed before filter()?
Only the limited prefix is available to downstream operations.
System.out.println(Stream.of(1,2,3,4,5,6)
.limit(3)
.filter(n -> n % 2 == 0)
.toList());
Output
[2]
176. What happens when filter() is placed before limit()?
The stream finds matching elements first, then limits them.
System.out.println(Stream.of(1,2,3,4,5,6)
.filter(n -> n % 2 == 0)
.limit(3)
.toList());
Output
[2, 4, 6]
177. What is the output when skip() follows limit()?
Operations execute in pipeline order.
System.out.println(IntStream.rangeClosed(1,10)
.boxed()
.limit(6)
.skip(2)
.toList());
Output
[3, 4, 5, 6]
178. What is the output when limit() follows skip()?
Skip first, then take the requested count.
System.out.println(IntStream.rangeClosed(1,10)
.boxed()
.skip(2)
.limit(4)
.toList());
Output
[3, 4, 5, 6]
179. How do you take values while a condition remains true?
Java 9+ provides takeWhile().
System.out.println(Stream.of(2,4,6,7,8,10)
.takeWhile(n -> n % 2 == 0)
.toList());
Output
[2, 4, 6]
180. How do you drop values while a condition remains true?
Java 9+ provides dropWhile().
System.out.println(Stream.of(2,4,6,7,8,10)
.dropWhile(n -> n % 2 == 0)
.toList());
Output
[7, 8, 10]
181. How do you create a parallel Stream?
Call parallelStream() on a collection.
List<Integer> list = List.of(1,2,3,4);
int sum = list.parallelStream().mapToInt(Integer::intValue).sum();
System.out.println(sum);
Output
10
Interview follow-up: When is a parallel stream actually beneficial?
182. How do you convert a sequential Stream to parallel?
Call parallel().
Stream<Integer> s = Stream.of(1,2,3).parallel();
System.out.println(s.isParallel());
Output
true
183. How do you convert a parallel Stream back to sequential?
Call sequential().
Stream<Integer> s = Stream.of(1,2,3).parallel().sequential();
System.out.println(s.isParallel());
Output
false
184. Why can forEach() on a parallel Stream print out of order?
forEach() does not guarantee encounter order in a parallel pipeline. Use forEachOrdered() when order matters.
List<Integer> result = Collections.synchronizedList(new ArrayList<>());
IntStream.rangeClosed(1,5).parallel().forEachOrdered(result::add);
System.out.println(result);
Output
[1, 2, 3, 4, 5]
185. What is forEachOrdered() used for?
It preserves encounter order even for ordered parallel streams.
List<String> result = Collections.synchronizedList(new ArrayList<>());
Stream.of("A","B","C").parallel().forEachOrdered(result::add);
System.out.println(result);
Output
[A, B, C]
186. Why are side effects risky in Streams?
Mutating external shared state can make code unsafe and unpredictable, especially in parallel streams.
List<Integer> source = List.of(1,2,3,4);
List<Integer> safe = source.stream()
.map(n -> n * 10)
.toList();
System.out.println(safe);
Output
[10, 20, 30, 40]
Interview follow-up: Prefer transformations and collectors over mutating external containers.
187. How do you safely collect a parallel Stream?
Use a proper collector rather than manually mutating a shared list.
List<Integer> result = IntStream.rangeClosed(1,5)
.parallel()
.boxed()
.map(n -> n * 2)
.toList();
System.out.println(result);
Output
[2, 4, 6, 8, 10]
188. What happens if reduce uses a non-associative operation in parallel?
Parallel reduction requires an associative accumulator to be reliable. Subtraction is not associative.
int sequential = Stream.of(10,2,1)
.reduce(0, (a,b) -> a - b);
System.out.println(sequential);
Output
-13
Interview follow-up: Why is subtraction unsafe as a parallel reduction accumulator?
189. How do you combine two Streams?
Use Stream.concat().
System.out.println(Stream.concat(
Stream.of("A","B"),
Stream.of("C","D")
).toList());
Output
[A, B, C, D]
190. How do you build a Stream using Stream.Builder?
Use the builder, add elements, then build.
Stream.Builder<String> b = Stream.builder();
b.add("Java");
b.add("SQL");
System.out.println(b.build().toList());
Output
[Java, SQL]
191. How do you use a custom Collector-like three-argument collect()?
Supply a result container, accumulator, and combiner.
ArrayList<Integer> result = Stream.of(1,2,3)
.collect(
ArrayList::new,
ArrayList::add,
ArrayList::addAll
);
System.out.println(result);
Output
[1, 2, 3]
192. How do you collect strings into a StringBuilder?
Use the mutable three-argument collect().
StringBuilder sb = Stream.of("Java","Stream","API")
.collect(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append
);
System.out.println(sb);
Output
JavaStreamAPI
193. How do you flatten Optional values in a Stream?
Java 9+ provides Optional.stream().
List<String> result = Stream.of(
Optional.of("Java"),
Optional.empty(),
Optional.of("SQL")
).flatMap(Optional::stream).toList();
System.out.println(result);
Output
[Java, SQL]
194. How do you stream a nullable value safely?
Java 9+ Stream.ofNullable() produces zero or one element.
System.out.println(Stream.ofNullable(null).count());
System.out.println(Stream.ofNullable("Java").count());
Output
0
1
195. How do you find whether two collections share any element?
Put one collection into a Set, then use anyMatch() on the other.
Set<Integer> a = Set.of(1,2,3);
boolean common = Stream.of(7,3,9).anyMatch(a::contains);
System.out.println(common);
Output
true
196. How do you find the intersection of two lists?
Filter one list using a Set built from the other.
List<Integer> a = List.of(1,2,3,4);
Set<Integer> b = Set.of(3,4,5);
System.out.println(a.stream().filter(b::contains).toList());
Output
[3, 4]
197. How do you find elements present in the first list but not the second?
Filter with negated membership.
List<Integer> a = List.of(1,2,3,4);
Set<Integer> b = Set.of(3,4,5);
System.out.println(a.stream().filter(n -> !b.contains(n)).toList());
Output
[1, 2]
198. How do you merge two lists and remove duplicates?
Concatenate streams and apply distinct().
List<Integer> a = List.of(1,2,3);
List<Integer> b = List.of(3,4,5);
System.out.println(Stream.concat(a.stream(), b.stream())
.distinct()
.toList());
Output
[1, 2, 3, 4, 5]
199. How do you verify that a list is sorted ascending using Streams?
Compare adjacent indexes with an IntStream.
List<Integer> list = List.of(1,2,4,7,9);
boolean sorted = IntStream.range(0, list.size() - 1)
.allMatch(i -> list.get(i) <= list.get(i + 1));
System.out.println(sorted);
Output
true
200. How do you find the first duplicate while preserving encounter order?
A Set can track previously seen values. This is stateful and is best kept sequential.
Set<Integer> seen = new HashSet<>();
Integer duplicate = Stream.of(4,2,7,2,9,4)
.filter(n -> !seen.add(n))
.findFirst()
.orElse(null);
System.out.println(duplicate);
Output
2
Interview follow-up: An interviewer may ask why this stateful predicate should not be used in a parallel Stream.
Interview Preparation Notes
The most frequently recurring Java Stream interview patterns include:
filter()andmap()map()vsflatMap()- Intermediate vs terminal operations
- Lazy evaluation
findFirst(),findAny(),anyMatch(),allMatch(), andnoneMatch()distinct(),sorted(),limit(), andskip()reduce()- Primitive Streams
Collectors.toMap()groupingBy()partitioningBy()- Highest salary and second-highest salary
- Highest salary by department
- Employees above average salary
- Duplicate elements
- First non-repeating character
- Word and character frequency
- Parallel Streams and side effects
- Stream reuse
- Short-circuiting
peek()Optionalintegration
For broader Java and company interview preparation, see:
- TCS Interview Questions 2026
- Interview Assistant Guide
- Cheapest AI Interview Assistant in 2026
- Best Chiku AI Alternative
- Best Parakeet AI Alternative
- Best LockedIn AI Alternatives
Use interview-assistance tools only where permitted by the interviewer, employer, assessment platform, and applicable rules.
How to Prepare Java Streams for Interviews
The best way to prepare is to solve these questions without copying the answer first.
For each problem:
- Write the traditional loop-based solution.
- Rewrite it using Streams.
- Explain each intermediate operation.
- Identify the terminal operation.
- State whether the pipeline is lazy.
- Discuss time and space complexity.
- Decide whether parallelization would be safe.
- Explain how you would handle nulls, duplicates, and empty input.
A common interview pattern is to start with something simple such as:
Then the interviewer may extend it:
Then:
Then:
Then:
That is why understanding the Stream pipeline matters more than memorizing individual snippets.
Related Interview Preparation Guides
Continue preparing with:
- TCS Interview Questions 2026
- Interview Assistant Guide
- Cheapest AI Interview Assistant in 2026
- Best Chiku AI Alternative
- Best Parakeet AI Alternative
- Best LockedIn AI Alternatives
You can also use InterviewAssist for permitted mock-interview and practice workflows using your own resume and job description.
Frequently Asked Questions
Are Java Streams important for interviews?
Yes. Java Streams are commonly tested in Java 8+ interviews because they reveal whether a candidate understands collections, functional programming, lambdas, method references, collectors, Optional, and data transformation.
What Stream methods should I prepare first?
Start with:
filter()map()flatMap()distinct()sorted()limit()skip()findFirst()anyMatch()allMatch()reduce()collect()groupingBy()partitioningBy()
What is the difference between intermediate and terminal Stream operations?
Intermediate operations return another Stream and are generally lazy. Examples include filter(), map(), and sorted().
Terminal operations produce a result or side effect and trigger pipeline execution. Examples include collect(), count(), reduce(), and forEach().
What is the difference between map() and flatMap()?
map() transforms one element into one result.
flatMap() transforms one element into a Stream or collection-like sequence and then flattens the nested results into one Stream.
Why are Java Streams lazy?
Laziness allows the runtime to avoid unnecessary work and enables short-circuiting operations such as findFirst(), limit(), and anyMatch().
Can a Stream be reused?
No. Once a terminal operation consumes a Stream, that Stream cannot be used again.
Are parallel Streams always faster?
No. Parallel Streams introduce splitting, scheduling, synchronization, and merge overhead. They are most useful for sufficiently large, CPU-intensive, easily partitionable workloads with stateless operations.
Should I use peek() for business logic?
Usually no. peek() is primarily intended for observing elements during debugging. Business transformations should normally be performed with operations such as map(), filter(), or collectors.
What are the most common Java Stream coding questions?
Common patterns include:
- Find duplicates
- Find frequency of characters or words
- Find the first non-repeating character
- Second-highest number
- Highest salary
- Highest salary by department
- Group employees
- Partition data
- Flatten nested lists
- Find values above average
- Sort custom objects
- Convert lists into maps
How many Java Stream questions should I practice?
It is better to master 30–50 patterns deeply than memorize 200 answers. This article provides 200 variations so you can practice the same concepts in different forms.
Research Basis
This article was synthesized from recurring Java 8/Stream topics found in public interview-experience reports and commonly used Java interview preparation resources. Reported examples include:
- TCS: Stream API concepts and filtering employee names by prefix.
- Infosys: highest salary per department, employees above average salary, and chaining multiple Stream filters.
- Coforge: non-repeating characters, Collection vs Stream, and intermediate vs terminal operations.
- ZEE5: finding duplicates using Java Streams.
- EPAM community interview reports: Java 8/Streams coding focus and string transformation.
- Java developer communities: repeated reports of
map()vsflatMap(),skip()/limit(), frequency problems, salary problems, and Stream-based string/array coding.
The exact wording and code examples here are original and randomized for practice.

