Java 8 Stream max()
and min()
Methods
Introduction
Java 8 introduced the Stream API, which provides various methods to process collections in a functional and declarative way. Among these, the max()
and min()
methods are used to find the maximum and minimum elements in a stream based on a comparator.
In this blog, we will explore:
✅ How max()
and min()
work
✅ Their syntax and examples
✅ Differences between max()
, min()
, and reduce()
✅ Common interview questions
1. Understanding max()
and min()
max(Comparator<T>)
returns the maximum element of the stream based on the given comparator.min(Comparator<T>)
returns the minimum element of the stream based on the given comparator.
These are terminal operations, meaning that once invoked, the stream pipeline is closed, and no further operations can be applied.
2. Syntax of max()
and min()
Optional<T> max(Comparator<? super T> comparator);
Optional<T> min(Comparator<? super T> comparator);
Since the result may be empty (in case of an empty stream), these methods return an Optional<T>
to avoid NullPointerException
.
3. Finding Maximum and Minimum in a List
Example: Finding the Maximum and Minimum Number
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class StreamMaxMinExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 45, 2, 30, 5);
// Finding the Maximum Number
Optional<Integer> maxNumber = numbers.stream().max(Integer::compareTo);
maxNumber.ifPresent(num -> System.out.println("Maximum Number: " + num));
// Finding the Minimum Number
Optional<Integer> minNumber = numbers.stream().min(Integer::compareTo);
minNumber.ifPresent(num -> System.out.println("Minimum Number: " + num));
}
}
--------------OUTPUT-----------
Maximum Number: 45
Minimum Number: 2
4. Finding Maximum and Minimum in Custom Objects
When working with objects, we need to provide a custom comparator.
Example: Finding the Oldest and Youngest Employee
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
class Employee {
String name;
int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + " years)";
}
}
public class StreamMaxMinEmployee {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", 25),
new Employee("Bob", 30),
new Employee("Charlie", 28),
new Employee("David", 35)
);
// Finding the Oldest Employee
Optional<Employee> oldestEmployee = employees.stream().max(Comparator.comparingInt(emp -> emp.age));
oldestEmployee.ifPresent(emp -> System.out.println("Oldest Employee: " + emp));
// Finding the Youngest Employee
Optional<Employee> youngestEmployee = employees.stream().min(Comparator.comparingInt(emp -> emp.age));
youngestEmployee.ifPresent(emp -> System.out.println("Youngest Employee: " + emp));
}
}
------------------------OUTPUT--------------------
Oldest Employee: David (35 years)
Youngest Employee: Alice (25 years)
5. Handling an Empty Stream with Optional
Since max()
and min()
return an Optional
, we must handle the case when the stream is empty.
List<Integer> emptyList = Arrays.asList();
Optional<Integer> maxValue = emptyList.stream().max(Integer::compareTo);
System.out.println(maxValue.orElse(-1)); // Output: -1 (fallback value)
6. Using max()
and min()
on Strings
max()
and min()
can also be used on strings.
Example: Find the Longest and Shortest String
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class StreamStringMaxMin {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "kiwi", "pineapple");
// Finding the longest word
Optional<String> longestWord = words.stream().max((s1, s2) -> s1.length() - s2.length());
longestWord.ifPresent(word -> System.out.println("Longest Word: " + word));
// Finding the shortest word
Optional<String> shortestWord = words.stream().min((s1, s2) -> s1.length() - s2.length());
shortestWord.ifPresent(word -> System.out.println("Shortest Word: " + word));
}
}
-------------------------output------------
Longest Word: pineapple
Shortest Word: kiwi
7. Difference Between max()
, min()
, and reduce()
Example of reduce()
for Max
List<Integer> numbers = Arrays.asList(10, 45, 2, 30, 5);
Optional<Integer> maxValue = numbers.stream().reduce(Integer::max);
System.out.println(maxValue.orElse(-1)); // Output: 45
8. Common Interview Questions on max()
and min()
Q1: What happens if the stream is empty when calling max()
or min()
?
✅ It returns Optional.empty()
, so we should handle it using orElse()
or orElseThrow()
.
Q2: Can we use max()
and min()
with parallel streams?
✅ Yes, but ensure that the comparator used is stateless and does not rely on mutable data.
Q3: How do you find the second largest number using streams?
✅ You can sort and limit the stream.
List<Integer> numbers = Arrays.asList(10, 45, 2, 30, 5);
Optional<Integer> secondMax = numbers.stream()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
System.out.println(secondMax.orElse(-1)); // Output: 30
2. How do you remove duplicates from a list using Streams?
✅ Trick: Use .distinct()
or Collectors.toSet()
.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveDuplicates {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 3, 7, 2, 5, 3, 8, 9, 2);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Unique Numbers: " + uniqueNumbers);
}
}
3. Can you find the most frequent element in a list?
✅ Trick: Use Collectors.groupingBy()
and max()
import java.util.*;
import java.util.stream.Collectors;
public class MostFrequentElement {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
String mostFrequent = words.stream()
.collect(Collectors.groupingBy(word -> word, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue()) // Get max count
.get()
.getKey();
System.out.println("Most Frequent Element: " + mostFrequent);
}
}
4. How do you merge two lists without duplicates using Streams?
✅ Trick: Use Stream.concat()
and distinct()
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MergeLists {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6);
List<Integer> mergedList = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println("Merged List: " + mergedList);
}
}
5. How do you find the longest string in a list?
✅ Trick: Use max()
with Comparator.comparingInt(String::length)
.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class LongestString {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "pineapple", "kiwi");
Optional<String> longestWord = words.stream()
.max((s1, s2) -> s1.length() - s2.length());
longestWord.ifPresent(word -> System.out.println("Longest Word: " + word));
}
}
6. Can you find the sum of all even numbers in a list?
✅ Trick: Use filter()
and reduce()
.
import java.util.Arrays;
import java.util.List;
public class SumOfEvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.reduce(0, Integer::sum);
System.out.println("Sum of Even Numbers: " + sum);
}
}
7. Can you find the first non-repeating character in a string?
✅ Trick: Use groupingBy()
and filter()
.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class FirstNonRepeatingChar {
public static void main(String[] args) {
String input = "swiss";
Character firstNonRepeating = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy
(c -> c, LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
System.out.println("First Non-Repeating Character: " + firstNonRepeating);
}
}
8. Can you check if two lists contain the same elements?
✅ Trick: Sort both lists and compare.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CompareLists {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(3, 1, 2);
List<Integer> list2 = Arrays.asList(2, 3, 1);
boolean areEqual = list1.stream().sorted().collect(Collectors.toList())
.equals(list2.stream().sorted().collect(Collectors.toList()));
System.out.println("Are Lists Equal? " + areEqual);
}
}
Happy Learning :)