How to use this guide
Read the problem, close the code section, write your own solution, then compare.
Describe what each intermediate operation does and which terminal operation triggers execution.
Consider empty lists, duplicate values, ties, null inputs and missing second-highest values.
Some included algorithm questions use a stack, a sliding window, a priority queue or a map because those are appropriate tools.
main() as noted below.Java 8 concepts quick revision
filter(), map(), flatMap(), distinct(), sorted(), limit(), skip(), peek()
collect(), forEach(), count(), min(), max(), reduce(), findFirst(), anyMatch(), allMatch(), noneMatch()
groupingBy(), partitioningBy(), counting(), mapping(), joining(), toMap(), summingDouble()
IntStream, mapToInt(), sum(), average(), Comparator, thenComparing()
All 66 programs with complete methods
Use search to find a program by title, number, or concept. Expand a heading to view the full method code.
Showing 66 programs
01Find even numbersfilter()
public static void findEvenNumbers(List<Integer> numbers) {
System.out.println("\n1. Even Numbers:");
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
02Find duplicate numbersgroupingBy(), counting()
public static void findDuplicateNumbers(List<Integer> numbers) {
System.out.println("\n2. Duplicate Numbers:");
Set<Integer> duplicates = numbers.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(duplicates);
}
03Find first non-repeated charactergroupingBy(), LinkedHashMap
public static void findFirstNonRepeatedCharacter(String input) {
System.out.println("\n3. First Non-Repeated Character:");
Character result = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
System.out.println(result);
}
04Find second-highest distinct numberdistinct(), sorted(), skip()
public static void findSecondHighest(List<Integer> numbers) {
System.out.println("\n4. Second-Highest Number:");
Integer result = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElse(null);
System.out.println(result);
}
05Find third-highest distinct numberdistinct(), sorted(), skip()
public static void findThirdHighest(List<Integer> numbers) {
System.out.println("\n5. Third-Highest Number:");
Integer result = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(2)
.findFirst()
.orElse(null);
System.out.println(result);
}
06Find maximum and minimummax(), min()
public static void findMaxAndMin(List<Integer> numbers) {
System.out.println("\n6. Maximum and Minimum:");
Integer max = numbers.stream()
.max(Integer::compareTo)
.orElse(null);
Integer min = numbers.stream()
.min(Integer::compareTo)
.orElse(null);
System.out.println("Maximum: " + max);
System.out.println("Minimum: " + min);
}
07Sort employees by salarysorted(), Comparator
public static void sortEmployeesBySalary(List<Employee> employees) {
System.out.println("\n7. Employees Sorted by Salary:");
employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary))
.forEach(System.out::println);
}
08Find highest-paid employeemax()
public static void findHighestPaidEmployee(List<Employee> employees) {
System.out.println("\n8. Highest-Paid Employee:");
Employee result = employees.stream()
.max(Comparator.comparingDouble(Employee::getSalary))
.orElse(null);
System.out.println(result);
}
09Find highest-paid employee in each departmentgroupingBy(), maxBy()
public static void findHighestPaidByDepartment(
List<Employee> employees) {
System.out.println("\n9. Highest-Paid Employee by Department:");
Map<String, Optional<Employee>> result = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.maxBy(
Comparator.comparingDouble(
Employee::getSalary))));
result.forEach((department, employee) ->
System.out.println(department + " -> "
+ employee.orElse(null)));
}
10Calculate average salary by departmentaveragingDouble()
public static void averageSalaryByDepartment(
List<Employee> employees) {
System.out.println("\n10. Average Salary by Department:");
Map<String, Double> result = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)));
result.forEach((department, average) ->
System.out.println(department + " -> " + average));
}
11Count employees by departmentgroupingBy(), counting()
public static void countEmployeesByDepartment(
List<Employee> employees) {
System.out.println("\n11. Employee Count by Department:");
Map<String, Long> result = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()));
result.forEach((department, count) ->
System.out.println(department + " -> " + count));
}
12Group employees by departmentgroupingBy()
public static void groupEmployeesByDepartment(
List<Employee> employees) {
System.out.println("\n12. Group Employees by Department:");
Map<String, List<Employee>> result = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
result.forEach((department, list) -> {
System.out.println(department + ":");
list.forEach(System.out::println);
});
}
13Find employees earning above a thresholdfilter()
public static void findEmployeesAboveSalary(
List<Employee> employees) {
System.out.println("\n13. Employees Earning Above 80000:");
employees.stream()
.filter(e -> e.getSalary() > 80000)
.forEach(System.out::println);
}
14Convert employees to a mapCollectors.toMap()
public static void convertEmployeesToMap(
List<Employee> employees) {
System.out.println("\n14. Employee ID to Name Map:");
Map<Integer, String> result = employees.stream()
.collect(Collectors.toMap(
Employee::getId,
Employee::getName,
(existing, replacement) -> existing,
LinkedHashMap::new));
System.out.println(result);
}
15Find duplicate stringsgroupingBy(), counting()
public static void findDuplicateStrings(List<String> names) {
System.out.println("\n15. Duplicate Strings:");
Set<String> result = names.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(result);
}
16Partition numbers into even and oddpartitioningBy()
public static void partitionEvenAndOdd(List<Integer> numbers) {
System.out.println("\n16. Partition Even and Odd:");
Map<Boolean, List<Integer>> result = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("Even: " + result.get(true));
System.out.println("Odd: " + result.get(false));
}
17Sum numbers using reducereduce()
public static void sumUsingReduce(List<Integer> numbers) {
System.out.println("\n17. Sum Using reduce:");
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum: " + sum);
}
18Join stringsCollectors.joining()
public static void joinStrings(List<String> names) {
System.out.println("\n18. Join Strings:");
String result = names.stream()
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(result);
}
19Find longest stringmax()
public static void findLongestString(List<String> words) {
System.out.println("\n19. Longest String:");
String result = words.stream()
.max(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println(result);
}
20Sort a map by valuesentrySet().stream(), sorted()
public static void sortMapByValues(Map<String, Integer> scores) {
System.out.println("\n20. Sort Map by Values:");
Map<String, Integer> result = scores.entrySet()
.stream()
.sorted(Map.Entry.<String, Integer>comparingByValue()
.reversed())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a,
LinkedHashMap::new));
System.out.println(result);
}
21Find employee names starting with Amap(), filter()
public static void findNamesStartingWithA(List<Employee> employees) {
System.out.println("\n21. Find employee names starting with A:");
employees.stream()
.map(Employee::getName)
.filter(name -> name.startsWith("A"))
.forEach(System.out::println);
}
22Find employees by age rangefilter()
public static void findEmployeesByAgeRange(List<Employee> employees) {
System.out.println("\n22. Find employees aged between 25 and 35:");
employees.stream()
.filter(e -> e.getAge() >= 25 && e.getAge() <= 35)
.forEach(System.out::println);
}
23Find unique departmentsmap(), distinct()
public static void findUniqueDepartments(List<Employee> employees) {
System.out.println("\n23. Find employees aged between 25 and 35:");
employees.stream()
.map(Employee::getDepartment)
.distinct()
.forEach(System.out::println);
}
24Find second-lowest distinct salarydistinct(), sorted(), skip()
public static void findSecondLowestSalary(List<Employee> employees) {
System.out.println("\n24. Find second-lowest distinct salary:");
Double result = employees.stream()
.map(Employee::getSalary)
.distinct()
.sorted()
.skip(1)
.findFirst()
.orElse(null);
System.out.println(result);
}
25Find top 3 highest-paid employeessorted(), limit()
public static void findTopThreePaidEmployees(List<Employee> employees) {
System.out.println("\n25. Find top 3 highest-paid employees:");
employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary)
.reversed())
.limit(3)
.forEach(System.out::println);
}
26Calculate total salary by departmentgroupingBy(), summingDouble()
public static void totalSalaryByDepartment(List<Employee> employees) {
System.out.println("\n26. Calculate total salary by department:");
Map<String, Double> result = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.summingDouble(Employee::getSalary)));
System.out.println(result);
}
27Find department with most employeesgroupingBy(), counting(), max()
public static void findDepartmentWithMostEmployees(
List<Employee> employees) {
System.out.println("\n27. Find department with the most employees:");
Map.Entry<String, Long> result = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.orElse(null);
System.out.println(result);
}
28Find oldest employeemax()
public static void findOldestEmployee(List<Employee> employees) {
System.out.println("\n28. Find the oldest employee:");
Employee result = employees.stream()
.max(Comparator.comparingInt(Employee::getAge))
.orElse(null);
System.out.println(result);
}
29Convert employee names to uppercasemap()
public static void convertNamesToUppercase(List<Employee> employees) {
System.out.println("\n29. Convert employee names to uppercase:");
employees.stream()
.map(Employee::getName)
.map(String::toUpperCase)
.forEach(System.out::println);
}
30Find common elements between two listsfilter(), contains(), distinct()
public static void findCommonElements(
List<Integer> first, List<Integer> second) {
System.out.println("\n30. Find common elements between two lists:");
Set<Integer> lookup = new HashSet<>(second);
List<Integer> result = first.stream()
.filter(lookup::contains)
.distinct()
.collect(Collectors.toList());
System.out.println(result);
}
31Flatten a list of listsflatMap()
public static void flattenNestedLists(List<List<Integer>> nestedLists) {
System.out.println("\n31. Flatten a list of lists:");
List<Integer> result = nestedLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(result);
}
32Find word frequencygroupingBy(), counting()
public static void findWordFrequency(List<String> words) {
System.out.println("\n32. Find word frequency:");
Map<String, Long> result = words.stream()
.collect(Collectors.groupingBy(
word -> word,
Collectors.counting()));
System.out.println(result);
}
33Group strings by lengthgroupingBy()
public static void groupStringsByLength(List<String> words) {
System.out.println("\n33. Group strings by their length:");
Map<Integer, List<String>> result = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(result);
}
34Sum even numbersfilter(), mapToInt(), sum()
public static void sumEvenNumbers(List<Integer> numbers) {
System.out.println("\n34. Sum even numbers:");
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum);
}
35Check whether any employee earns above 100000anyMatch()
public static void checkAnyHighSalary(List<Employee> employees) {
System.out.println("\n35. Check whether any employee earns over 100000:");
boolean result = employees.stream()
.anyMatch(e -> e.getSalary() > 100000);
System.out.println(result);
}
36Check whether all employees are adultsallMatch()
public static void checkAllAdults(List<Employee> employees) {
System.out.println("\n36. Check whether all employees are adults (18 or older):");
boolean result = employees.stream()
.allMatch(e -> e.getAge() >= 18);
System.out.println(result);
}
37Check whether no employee belongs to HRnoneMatch()
public static void checkNoHrEmployees(List<Employee> employees) {
System.out.println("\n37. Check whether no employee belongs to HR:");
boolean result = employees.stream()
.noneMatch(e -> "HR".equals(e.getDepartment()));
System.out.println(result);
}
38Find first employee whose name starts with Sfilter(), findFirst()
public static void findFirstEmployeeStartingWithS(
List<Employee> employees) {
System.out.println("\n38. Find first employee whose name starts with S:");
Employee result = employees.stream()
.filter(e -> e.getName().startsWith("S"))
.findFirst()
.orElse(null);
System.out.println(result);
}
39Find most frequently occurring numbergroupingBy(), counting(), max()
public static void findMostFrequentNumber(List<Integer> numbers) {
System.out.println("\n39. Find the most frequently occurring number:");
Map.Entry<Integer, Long> result = numbers.stream()
.collect(Collectors.groupingBy(
n -> n,
Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.orElse(null);
System.out.println(result);
}
40Remove duplicates and sort descendingdistinct(), sorted()
public static void removeDuplicatesAndSortDescending(
List<Integer> numbers) {
System.out.println("\n40. Remove duplicates and sort descending:");
List<Integer> result = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(result);
}
41Count repeating and non-repeating charactersgroupingBy(), counting()
public static void findRepeatingCharactersCount() {
System.out.println("\n41. Count repeating and non-repeating characters");
String input = "programming";
Map<Character, Long> charCount = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()));
charCount.forEach((ch, count) ->
System.out.println(ch + " : " + count));
long repeatingCount = charCount.values().stream()
.filter(count -> count > 1)
.count();
long nonRepeatingCount = charCount.values().stream()
.filter(count -> count == 1)
.count();
System.out.println("Repeating characters count: " + repeatingCount);
System.out.println("Non-repeating characters count: " + nonRepeatingCount);
charCount.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.ifPresent(ch ->
System.out.println("First non-repeating character: " + ch));
}
42Find longest common suffixmap(), reduce()
public static void commonSuffixFinder(List<String> words) {
System.out.println("\n42. Find the longest common suffix");
if (words == null || words.isEmpty()) {
System.out.println("Common suffix: ");
return;
}
String commonPrefix = words.stream()
.filter(Objects::nonNull)
.map(s -> new StringBuilder(s).reverse().toString())
.reduce((s1, s2) -> {
int i = 0;
int minLength = Math.min(s1.length(), s2.length());
while (i < minLength && s1.charAt(i) == s2.charAt(i)) {
i++;
}
return s1.substring(0, i);
})
.orElse("");
String suffix = new StringBuilder(commonPrefix).reverse().toString();
System.out.println("Longest common suffix: " + suffix);
}
43Find index of a target element in an arrayIntStream.range(), filter(), findFirst()
public static void findArrayIndexForTargetElement() {
System.out.println("\n43. Find the index of a target element");
int[] arr = {10, 20, 30, 40, 50, 60, 90, 102, 104, 56, 79};
int target = 56;
int index = IntStream.range(0, arr.length)
.filter(i -> arr[i] == target)
.findFirst()
.orElse(-1);
System.out.println("Index of " + target + ": " + index);
}
44Find pairs whose sum equals a targetHashSet lookup
public static void findIntegerArrayPairs() {
System.out.println("\n44. Find pairs whose sum equals a target");
int[] numbers = {1, 6, 5, 2, 4, 9};
int targetSum = 10;
Set<Integer> seen = new HashSet<>();
Set<String> pairs = new LinkedHashSet<>();
for (int number : numbers) {
int complement = targetSum - number;
if (seen.contains(complement)) {
int first = Math.min(number, complement);
int second = Math.max(number, complement);
pairs.add("(" + first + ", " + second + ")");
}
seen.add(number);
}
if (pairs.isEmpty()) {
System.out.println("No pairs found");
} else {
pairs.forEach(pair -> System.out.println("Pair found: " + pair));
}
}
45Validate balanced bracketsDeque / stack
public static boolean isValidExpression(String str) {
System.out.println("\n45. Validate balanced brackets");
if (str == null) {
return false;
}
Deque<Character> stack = new ArrayDeque<>();
for (char ch : str.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((ch == ')' && top != '(')
|| (ch == '}' && top != '{')
|| (ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
46Group anagramsgroupingBy()
public static List<List<String>> groupAnagrams(String[] input) {
System.out.println("\n46. Group anagrams");
List<List<String>> result = Arrays.stream(input)
.collect(Collectors.groupingBy(word -> {
char[] chars = word.toLowerCase(Locale.ROOT).toCharArray();
Arrays.sort(chars);
return new String(chars);
}))
.values()
.stream()
.collect(Collectors.toList());
result.forEach(System.out::println);
return result;
}
47Convert a string to an integer (myAtoi)String parsing and overflow checks
public static int myAtoi(String s) {
System.out.println("\n47. Convert a string to an integer");
if (s == null) {
throw new IllegalArgumentException("Input cannot be null");
}
int i = 0;
int sign = 1;
long result = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
if (i < s.length() && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
sign = s.charAt(i++) == '-' ? -1 : 1;
}
int start = i;
while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
result = result * 10 + (s.charAt(i) - '0');
long value = result * sign;
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
throw new NumberFormatException("Integer overflow");
}
i++;
}
if (i == start) {
throw new NumberFormatException("No digits found");
}
return (int) (result * sign);
}
48Remove duplicates from an arrayLinkedHashSet
public static <T> T[] removeDuplicates(T[] array) {
System.out.println("\n48. Remove duplicates from an array");
return new LinkedHashSet<>(Arrays.asList(array))
.toArray(Arrays.copyOf(array, 0));
}
49Find longest substring without repeating charactersSliding window
public static String findLongestUniqueSubstring(String s) {
System.out.println("\n49. Find the longest substring without repeating characters");
if (s == null || s.isEmpty()) {
return "";
}
Map<Character, Integer> lastSeen = new HashMap<>();
int start = 0, maxStart = 0, maxLength = 0;
for (int end = 0; end < s.length(); end++) {
char ch = s.charAt(end);
if (lastSeen.containsKey(ch)) {
start = Math.max(lastSeen.get(ch) + 1, start);
}
lastSeen.put(ch, end);
if (end - start + 1 > maxLength) {
maxLength = end - start + 1;
maxStart = start;
}
}
return s.substring(maxStart, maxStart + maxLength);
}
50Find longest word in a sentenceArrays.stream(), max()
public static void findLargestStringFromGivenString() {
System.out.println("\n50. Find the longest word in a sentence");
String sentence =
"Java 8 introduced Stream API which simplifies bulk operations on collections";
String result = Arrays.stream(sentence.split("\\s+"))
.max(Comparator.comparingInt(String::length))
.orElse("");
System.out.println("Longest word: " + result);
}
51Count numbers that occur more than oncegroupingBy(), counting()
public static void findCountPairsCount() {
System.out.println("\n51. Count numbers that occur more than once");
List<Integer> numbers = Arrays.asList(
5, 3, 4, 2, 5, 5, 4, 3, 2, 2, 1, 7, 9);
Map<Integer, Long> countMap = numbers.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()));
long repeatingCount = countMap.values().stream()
.filter(count -> count > 1)
.count();
System.out.println("Distinct repeating values: " + repeatingCount);
countMap.forEach((number, count) ->
System.out.println("Number: " + number + ", Count: " + count));
}
52Aggregate and reduction functionscount(), sum(), average(), min(), max(), reduce()
public static void reductionAggregateFunctions() {
System.out.println("\n52. Aggregate and Reduction Functions");
List<Integer> list = Arrays.asList(
5, 3, 4, 2, 5, 5, 4, 3, 2, 2, 1, 7, 9);
long count = list.stream().count();
System.out.println("Count: " + count);
int sum = list.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
OptionalDouble avg = list.stream()
.mapToInt(Integer::intValue)
.average();
System.out.println("Average: " + avg.orElse(0.0));
Optional<Integer> min = list.stream()
.min(Integer::compareTo);
System.out.println("Minimum: " + min.orElse(null));
Optional<Integer> max = list.stream()
.max(Integer::compareTo);
System.out.println("Maximum: " + max.orElse(null));
Optional<Integer> reduceSum = list.stream()
.reduce(Integer::sum);
System.out.println("Reduce sum: " + reduceSum.orElse(0));
int reduceSum1 = list.stream()
.reduce(0, Integer::sum);
System.out.println("Reduce with identity: " + reduceSum1);
int total = list.stream()
.collect(Collectors.summingInt(Integer::intValue));
System.out.println("Collectors summingInt: " + total);
IntSummaryStatistics stats = list.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Statistics: " + stats);
Map<Integer, Long> groupCount = list.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()));
System.out.println("Number frequency: " + groupCount);
}
53Terminal operationsforEach(), collect(), match, find, custom Collector
public static void terminalOperations() {
System.out.println("\n53. Terminal Operations");
List<String> names = Arrays.asList(
"Alice", "Bob", "Charlie");
// forEach()
System.out.println("forEach():");
names.stream().forEach(System.out::println);
// toArray()
String[] nameArray = names.stream()
.toArray(String[]::new);
System.out.println("toArray(): "
+ Arrays.toString(nameArray));
// collect()
List<String> list = names.stream()
.collect(Collectors.toList());
System.out.println("collect(): " + list);
Set<String> set = names.stream()
.collect(Collectors.toSet());
System.out.println("toSet(): " + set);
// joining()
String joined = names.stream()
.collect(Collectors.joining(", "));
System.out.println("joining(): " + joined);
// anyMatch()
boolean anyStartsWithA = names.stream()
.anyMatch(s -> s.startsWith("A"));
System.out.println("anyMatch(A): " + anyStartsWithA);
// allMatch()
boolean allHaveLength3 = names.stream()
.allMatch(s -> s.length() == 3);
System.out.println("allMatch(length == 3): "
+ allHaveLength3);
// noneMatch()
boolean noneStartWithZ = names.stream()
.noneMatch(s -> s.startsWith("Z"));
System.out.println("noneMatch(Z): " + noneStartWithZ);
// findFirst()
Optional<String> first = names.stream().findFirst();
System.out.println("findFirst(): " + first.orElse("Not found"));
// findAny()
Optional<String> any = names.parallelStream().findAny();
System.out.println("findAny(): " + any.orElse("Not found"));
// forEachOrdered()
System.out.println("forEachOrdered():");
names.parallelStream().forEachOrdered(System.out::println);
// Custom Collector
Collector<String, StringJoiner, String> customCollector =
Collector.of(
() -> new StringJoiner(" | "),
StringJoiner::add,
StringJoiner::merge,
StringJoiner::toString);
String result = names.stream().collect(customCollector);
System.out.println("Custom Collector: " + result);
}
54Intermediate operationsfilter(), map(), flatMap(), distinct(), limit(), skip(), sorted(), peek()
public static void intermediateOperations() {
System.out.println("\n54. Intermediate Operations");
List<String> names = Arrays.asList(
"Alice", "Bob", "Charlie");
IntStream intStream = IntStream.range(0, 20);
// filter()
List<Integer> evenNumbers = intStream.boxed()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("filter(): " + evenNumbers);
// map()
List<String> upperCaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("map(): " + upperCaseNames);
// flatMap()
List<List<String>> data = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d"));
List<String> flat = data.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println("flatMap(): " + flat);
// distinct()
List<Integer> unique = Arrays.asList(1, 2, 2, 3, 3, 4)
.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("distinct(): " + unique);
// limit()
List<Integer> limited = Stream.of(1, 2, 3, 4, 5)
.limit(3)
.collect(Collectors.toList());
System.out.println("limit(): " + limited);
// skip()
List<Integer> skipped = Stream.of(1, 2, 3, 4, 5)
.skip(2)
.collect(Collectors.toList());
System.out.println("skip(): " + skipped);
// sorted()
List<String> sorted = names.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("sorted(): " + sorted);
// sorted() using string length
List<String> sortedByLength = names.stream()
.sorted(Comparator.comparingInt(String::length)
.reversed())
.collect(Collectors.toList());
System.out.println("sorted by length descending: "
+ sortedByLength);
// peek()
List<String> result = names.stream()
.peek(name -> System.out.println("Processing: " + name))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("Final result: " + result);
}
55Partition a list into even and odd numberspartitioningBy()
public static void partitionListEvenAndOdd() {
System.out.println("\n55. Partition List into Even and Odd Numbers");
List<Integer> numbers = Arrays.asList(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("Even numbers: " + partitioned.get(true));
System.out.println("Odd numbers: " + partitioned.get(false));
}
56Find second-highest distinct numberdistinct(), sorted(), skip()
public static void findSecondHighestNumber() {
System.out.println("\n56. Find the Second-Highest Distinct Number");
List<Integer> numbers = Arrays.asList(
10, 50, 20, 80, 80, 60, 50, 70);
Integer secondHighest = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElseThrow(() ->
new NoSuchElementException(
"Second-highest number does not exist"));
System.out.println("Second-highest number: " + secondHighest);
}
57Find median using two priority queuesPriorityQueue (two heaps)
static class MedianFinder {
private PriorityQueue<Integer> low; // Max heap
private PriorityQueue<Integer> high; // Min heap
public MedianFinder() {
low = new PriorityQueue<>(Collections.reverseOrder());
high = new PriorityQueue<>();
}
public void addNum(int num) {
low.offer(num);
// Move the largest element from low to high
high.offer(low.poll());
// Keep low equal in size to high or one element larger
if (low.size() < high.size()) {
low.offer(high.poll());
}
}
public double findMedian() {
if (low.isEmpty()) {
throw new NoSuchElementException(
"Cannot find median of an empty collection");
}
if (low.size() == high.size()) {
return ((double) low.peek() + high.peek()) / 2.0;
}
return low.peek();
}
}
public static void findMedian() {
System.out.println("\n57. Find Median Using Two Priority Queues");
MedianFinder finder = new MedianFinder();
int[] numbers = {5, 15, 1, 3, 8, 7, 9, 10};
for (int number : numbers) {
finder.addNum(number);
System.out.println(
"Added: " + number
+ ", Current median: " + finder.findMedian());
}
}
58Merge two maps and concatenate valuesMap.merge()
public static void concatenationMapsDemo() {
System.out.println("\n58. Merge Two Maps and Concatenate Values");
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "One");
map1.put(2, "Two");
Map<Integer, String> map2 = new HashMap<>();
map2.put(3, "Three");
map2.put(4, "Four");
map2.put(2, "Latest");
// Merge map2 into map1
map2.forEach((key, value) ->
map1.merge(
key,
value,
(oldValue, newValue) ->
oldValue + ", " + newValue
));
System.out.println("Merged map:");
map1.forEach((key, value) ->
System.out.println(key + " = " + value));
}
59Filter employees earning > 50000 and group by departmentfilter(), groupingBy()
public static void filterAndGroupEmployeesBySalary(
List<Employee> empList) {
System.out.println(
"\n59. Filter employees with salary > 50000 and group by department");
Map<String, List<Employee>> filteredGrouped = empList.stream()
.filter(e -> e.getSalary() > 50000)
.collect(Collectors.groupingBy(Employee::getDepartment));
filteredGrouped.forEach((department, employees) -> {
System.out.println(department + " ->");
employees.forEach(System.out::println);
});
}
60Get employee names per departmentgroupingBy(), mapping()
public static void getEmployeeNamesByDepartment(
List<Employee> empList) {
System.out.println("\n60. Get employee names per department");
Map<String, List<String>> namesPerDept = empList.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.mapping(
Employee::getName,
Collectors.toList()
)
));
System.out.println(namesPerDept);
}
61Calculate total salary per department (screenshot variation)groupingBy(), summingDouble()
// 61. Calculate total salary per department (screenshot variation)
public static void totalSalaryByDepartmentFromScreenshot(List<Employee> empList) {
System.out.println("\n61. Calculate total salary per department");
Map<String, Double> totalSalaryByDept = empList.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.summingDouble(Employee::getSalary)));
totalSalaryByDept.forEach((department, total) ->
System.out.println(department + " -> " + total));
}
62Partition employees by salary thresholdpartitioningBy()
public static void partitionEmployeesBySalary(
List<Employee> empList) {
System.out.println("\n62. Partition employees by salary > 50000");
Map<Boolean, List<Employee>> partitioned = empList.stream()
.collect(Collectors.partitioningBy(
e -> e.getSalary() > 50000
));
System.out.println("Salary > 50000: " + partitioned.get(true));
System.out.println("Salary <= 50000: " + partitioned.get(false));
}
63List unique departments in sorted ordermap(), distinct(), sorted()
public static void listUniqueDepartmentsSorted(
List<Employee> empList) {
System.out.println("\n63. List unique departments in sorted order");
List<String> sortedDepts = empList.stream()
.map(Employee::getDepartment)
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedDepts);
}
64Sort employees by salary and then by namesorted(), thenComparing()
public static void sortEmployeesBySalaryThenName(
List<Employee> empList) {
System.out.println("\n64. Sort employees by salary and then by name");
List<Employee> sorted = empList.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary)
.thenComparing(Employee::getName))
.collect(Collectors.toList());
sorted.forEach(System.out::println);
}
65Collect employee names into a Set using mapping()Collectors.mapping(), toSet()
public static void customEmployeeNameCollector(
List<Employee> empList) {
System.out.println("\n65. Collect employee names using mapping collector");
Collector<Employee, ?, Set<String>> customCollector =
Collectors.mapping(
Employee::getName,
Collectors.toSet()
);
Set<String> names = empList.stream()
.collect(customCollector);
System.out.println(names);
}
66Find second-highest distinct employee salarymap(), distinct(), sorted(), skip()
public static void findSecondHighestEmployeeSalary(
List<Employee> empList) {
System.out.println("\n66. Find the second-highest distinct employee salary");
Optional<Double> secondHighest = empList.stream()
.map(Employee::getSalary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
if (secondHighest.isPresent()) {
System.out.println("Second-highest salary: "
+ secondHighest.get());
} else {
System.out.println(
"No second-highest distinct salary exists");
}
}
Complete main() method
This is the main method from your source file, including the sample data and calls to the numbered programs. Keep it alongside the program methods in the same class.
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(
10, 20, 30, 20, 40, 10, 50, 60, 80);
List<Employee> employees = Arrays.asList(
new Employee(101, "Rahul", "IT", 90000, 30),
new Employee(102, "Priya", "HR", 60000, 28),
new Employee(103, "Amit", "IT", 120000, 35),
new Employee(104, "Sneha", "Finance", 75000, 32),
new Employee(105, "Kiran", "HR", 65000, 31),
new Employee(106, "Ravi", "IT", 100000, 29),
new Employee(107, "Meena", "Finance", 85000, 36)
);
List<String> names = Arrays.asList(
"Java", "Spring", "Java", "Kafka", "Spring", "Docker");
List<String> words = Arrays.asList(
"Java", "Spring", "Microservices", "API");
Map<String, Integer> scores = new HashMap<>();
scores.put("Java", 90);
scores.put("Spring", 85);
scores.put("Kafka", 95);
scores.put("Docker", 80);
List<Integer> first = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> second = Arrays.asList(3, 4, 5, 7, 8);
List<List<Integer>> nestedLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
findEvenNumbers(numbers); // 1
findDuplicateNumbers(numbers); // 2
findFirstNonRepeatedCharacter("swiss"); // 3
findSecondHighest(numbers); // 4
findThirdHighest(numbers); // 5
findMaxAndMin(numbers); // 6
sortEmployeesBySalary(employees); // 7
findHighestPaidEmployee(employees); // 8
findHighestPaidByDepartment(employees); // 9
averageSalaryByDepartment(employees); // 10
countEmployeesByDepartment(employees); // 11
groupEmployeesByDepartment(employees); // 12
findEmployeesAboveSalary(employees); // 13
convertEmployeesToMap(employees); // 14
findDuplicateStrings(names); // 15
partitionEvenAndOdd(numbers); // 16
sumUsingReduce(numbers); // 17
joinStrings(names); // 18
findLongestString(words); // 19
sortMapByValues(scores); // 20
findNamesStartingWithA(employees); // 21
findEmployeesByAgeRange(employees); // 22
findUniqueDepartments(employees); // 23
findSecondLowestSalary(employees); // 24
findTopThreePaidEmployees(employees); // 25
totalSalaryByDepartment(employees); // 26
findDepartmentWithMostEmployees(employees); // 27
findOldestEmployee(employees); // 28
convertNamesToUppercase(employees); // 29
findCommonElements(first, second); // 30
flattenNestedLists(nestedLists); // 31
findWordFrequency(names); // 32
groupStringsByLength(names); // 33
sumEvenNumbers(numbers); // 34
checkAnyHighSalary(employees); // 35
checkAllAdults(employees); // 36
checkNoHrEmployees(employees); // 37
findFirstEmployeeStartingWithS(employees); // 38
findMostFrequentNumber(numbers); // 39
removeDuplicatesAndSortDescending(numbers); // 40
findRepeatingCharactersCount(); // 41
commonSuffixFinder(Arrays.asList(
"running", "jogging", "walking")); // 42
findArrayIndexForTargetElement(); // 43
findIntegerArrayPairs(); // 44
boolean valid = isValidExpression("({[]})");
System.out.println("Valid expression: " + valid); // 45
groupAnagrams(new String[]{
"eat", "tea", "tan", "ate", "nat", "bat"
}); // 46
System.out.println("Converted number: " + myAtoi("12345")); // 47
Integer[] values = {10, 20, 10, 30, 20, 40};
System.out.println("Unique array: "
+ Arrays.toString(removeDuplicates(values))); // 48
System.out.println("Longest unique substring: "
+ findLongestUniqueSubstring("abcabcbb")); // 49
findLargestStringFromGivenString(); // 50
findCountPairsCount(); // 51
reductionAggregateFunctions(); // 52
terminalOperations(); // 53
intermediateOperations(); // 54
partitionListEvenAndOdd(); // 55
findSecondHighestNumber(); // 56
findMedian(); // 57
concatenationMapsDemo(); // 58
filterAndGroupEmployeesBySalary(employees); // 59
getEmployeeNamesByDepartment(employees); // 60
totalSalaryByDepartmentFromScreenshot(employees); // 61
partitionEmployeesBySalary(employees); // 62
listUniqueDepartmentsSorted(employees); // 63
sortEmployeesBySalaryThenName(employees); // 64
customEmployeeNameCollector(employees); // 65
findSecondHighestEmployeeSalary(employees); // 66
}
totalSalaryByDepartmentFromScreenshot, because the original source already uses totalSalaryByDepartment(List<Employee>) for program 26. Change the call in main to totalSalaryByDepartmentFromScreenshot(employees) to invoke both separately. Program 57's helper class and demo method are both shown in its section.