Java Stream max() Example

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

1. Introduction

This tutorial explains how to use the max() method of the Java Stream API. The max() method is used to determine the maximum element of a stream according to a given comparator. This is a common operation when dealing with collections of data that require ordering or comparison.

Key Points

1. The max() method is used to find the maximum element in a stream based on a provided comparator.

2. It returns an Optional type because the stream may be empty.

3. The Java Stream max() method is a terminal operation that returns the largest element in the Stream.

2. Program Steps

1. Create a Stream of integers.

2. Apply the max() method with a comparator to find the largest number.

3. Handle the result wrapped in an Optional.

3. Code Program

import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;

public class StreamMaxExample {

    public static void main(String[] args) {
        // Stream of integers
        Stream<Integer> numberStream = Stream.of(10, 45, 75, 30, 90);

        // Find max in stream of numbers
        Optional<Integer> maxNumber = numberStream.max(Comparator.naturalOrder());
        maxNumber.ifPresent(max -> System.out.println("The maximum number is: " + max));

        // Stream of strings
        Stream<String> stringStream = Stream.of("Apple", "Orange", "Banana", "Lemon", "Peach");

        // Find max in stream of strings
        Optional<String> longestString = stringStream.max(Comparator.comparingInt(String::length));
        longestString.ifPresent(longest -> System.out.println("The longest string is: " + longest));
    }
}

Output:

The maximum number is: 90
The longest string is: Orange

Explanation:

1. Stream.of(10, 45, 75, 30, 90) creates a stream of integers.

2. numberStream.max(Comparator.naturalOrder()) applies the max() operation with the natural ordering of integers to find the highest value.

3. maxNumber.ifPresent(max -> System.out.println("The maximum number is: " + max)) checks if a maximum value is present and prints it.

4. Stream.of("Apple", "Orange", "Banana", "Lemon", "Peach") creates another stream, this time with strings.

5. stringStream.max(Comparator.comparingInt(String::length)) uses a comparator based on string length to find the longest string in the stream.

6. longestString.ifPresent(longest -> System.out.println("The longest string is: " + longest)) prints the longest string if it exists.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare