Stream Questions - Intermediate
1. Find the second highest number in a list
List<Integer> list = Arrays.asList(10, 30, 20, 50, 40);
Optional<Integer> secondHighest = list.stream()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
System.out.println(secondHighest.get());
2. Group strings by their length
List<String> words = Arrays.asList("apple", "bat", "cat", "banana", "kiwi");
Map<Integer, List<String>> grouped = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(grouped);
3. Count duplicate elements in a list
List<String> items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
Map<String, Long> duplicates = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
duplicates.entrySet().stream()
.filter(e -> e.getValue() > 1)
.forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
4. Partition a list of integers into even and odd
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(partitioned);
5. Find all palindromes in a list of strings
List<String> words = Arrays.asList("level", "", "radar", "python");
List<String> palindromes = words.stream()
.filter(w -> w.equals(new StringBuilder(w).reverse().toString()))
.collect(Collectors.toList());
System.out.println(palindromes);
6. Find the second highest number in a list
List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 7);
Optional<Integer> secondHighest = numbers.stream()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
System.out.println(secondHighest.orElse(null)); // Output: 7
7. Check if all elements are even
boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);
8. Group strings by their length
List<String> words = Arrays.asList("", "stream", "api", "code");
Map<Integer, List<String>> grouped = words.stream()
.collect(Collectors.groupingBy(String::length));
9. Count the frequency of each character in a string
String input = "banana";
Map<Character, Long> freq = input.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
10. Partition numbers into even and odd
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
11. Find the first repeated character
String str = "apple";
Set<Character> seen = new HashSet<>();
Optional<Character> repeated = str.chars()
.mapToObj(c -> (char) c)
.filter(c -> !seen.add(c))
.findFirst();
12. Flatten a list of lists
List<List<String>> nested = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d")
);
List<String> flat = nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
13. Sort by last character
List<String> list = Arrays.asList("apple", "banana", "cherry");
list.sort(Comparator.comparing(s -> s.charAt(s.length() - 1)));
14. Count words starting with a specific letter
long count = words.stream()
.filter(w -> w.startsWith("c"))
.count();
15. Sum of squares
int sum = numbers.stream()
.map(n -> n * n)
.reduce(0, Integer::sum);
16. Join strings with comma
String result = words.stream()
.collect(Collectors.joining(", "));
17. Find the product of all elements
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
18. Find longest string
Optional<String> longest = words.stream()
.max(Comparator.comparingInt(String::length));
19. Convert list to uppercase
List<String> upper = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
20. Extract distinct elements
List<Integer> distinct = numbers.stream()
.distinct()
.collect(Collectors.toList());
21. Find element frequency in list
Map<Integer, Long> freqMap = numbers.stream()
.collect(Collectors.groupingBy(n -> n, Collectors.counting()));
22. Find palindromes
List<String> palindromes = words.stream()
.filter(s -> new StringBuilder(s).reverse().toString().equals(s))
.collect(Collectors.toList());
23. Check if any number is greater than 10
boolean anyGreaterThanTen = numbers.stream().anyMatch(n -> n > 10);
24. Find numbers with duplicates
Set<Integer> seenNums = new HashSet<>();
List<Integer> duplicates = numbers.stream()
.filter(n -> !seenNums.add(n))
.collect(Collectors.toList());
25. Convert map to list of strings
Map<String, Integer> map = Map.of("A", 1, "B", 2);
List<String> result = map.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.toList());
26. Create a frequency map of words
Map<String, Long> wordFreq = words.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
27. Remove null values
List<String> cleaned = words.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
28. Find elements starting and ending with same letter
List<String> matches = words.stream()
.filter(w -> w.charAt(0) == w.charAt(w.length() - 1))
.collect(Collectors.toList());
29. Convert list of strings to list of lengths
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
30. Convert int array to List
int[] array = {1, 2, 3};
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
31. Filter top 3 largest numbers
List<Integer> top3 = numbers.stream()
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
32. Convert a string of numbers to a sum
String str = "1,2,3,4";
int total = Arrays.stream(str.split(","))
.mapToInt(Integer::parseInt)
.sum();
33. Find common elements between two lists
List<Integer> list1 = List.of(1, 2, 3);
List<Integer> list2 = List.of(2, 3, 4);
List<Integer> common = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
34. Convert list of strings to map of word-length
Map<String, Integer> map = words.stream()
.collect(Collectors.toMap(w -> w, String::length));
35. Filter prime numbers
boolean isPrime(int num) {
return num > 1 && IntStream.rangeClosed(2, (int)Math.sqrt(num))
.allMatch(n -> num % n != 0);
}
List<Integer> primes = numbers.stream()
.filter(n -> isPrime(n))
.collect(Collectors.toList());
36. Find longest palindrome
Optional<String> longestPalin = words.stream()
.filter(w -> w.equals(new StringBuilder(w).reverse().toString()))
.max(Comparator.comparingInt(String::length));
37. Sum all digits in a list of numbers
int sumOfDigits = numbers.stream()
.map(n -> String.valueOf(n).chars().map(Character::getNumericValue).sum())
.reduce(0, Integer::sum);
38. Find missing numbers from 1 to N
int N = 10;
Set<Integer> inputSet = new HashSet<>(numbers);
List<Integer> missing = IntStream.rangeClosed(1, N)
.filter(i -> !inputSet.contains(i))
.boxed()
.collect(Collectors.toList());
39. Convert a list of string numbers to integers
List<String> strNums = List.of("1", "2", "3");
List<Integer> intList = strNums.stream()
.map(Integer::parseInt)
.collect(Collectors.toList());
40. Find the average of all even numbers
OptionalDouble avg = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.average();
41. Count vowels in all strings
long vowels = words.stream()
.flatMapToInt(CharSequence::chars)
.filter(c -> "aeiou".indexOf(Character.toLowerCase(c)) != -1)
.count();
42. Get top 3 longest words
List<String> longestWords = words.stream()
.sorted(Comparator.comparingInt(String::length).reversed())
.limit(3)
.collect(Collectors.toList());
43. Convert list to Set (unique)
Set<String> unique = words.stream().collect(Collectors.toSet());
44. Find all strings that contain digits
List<String> withDigits = words.stream()
.filter(s -> s.matches(".*\\d.*"))
.collect(Collectors.toList());
45. Remove duplicate characters from string
String input = "banana";
String result = input.chars()
.distinct()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
46. Group employees by department name
Map<String, List<Employee>> groupedByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
47. Count the number of employees in each department
Map<String, Long> empCountByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
48. Find duplicate elements in a list
List<Integer> duplicates = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
49. Sort a list of strings by length
List<String> sortedByLength = strings.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
50. Partition numbers into even and odd
Map<Boolean, List<Integer>> evenOddPartition = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));