Java Collections max()

In this guide, you will learn about the Collections max() method in Java programming and how to use it with an example.

1. Collections max() Method Overview

Definition:

The max() method of the Collections class in Java is used to return the maximum element of the given collection, according to the natural ordering of its elements.

Syntax:

Collections.max(Collection<? extends T> coll)

Parameters:

coll: The collection whose maximum element is to be determined.

Key Points:

- The collection must not be empty, or else a NoSuchElementException will be thrown.

- All elements in the collection must be mutually comparable using the provided comparator (or the natural ordering if using the method without a comparator), otherwise, a ClassCastException is thrown.

- There is an overloaded version of max() that takes a custom comparator as an argument to determine the maximum element based on the comparator's ordering.

2. Collections max() Method Example


import java.util.*;

public class CollectionsMaxExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(15, 23, 7, 31, 12));

        // Finding the maximum number in the list
        int maxNumber = Collections.max(numbers);
        System.out.println("Maximum number in the list: " + maxNumber);

        // Finding the maximum string based on length using a custom comparator
        List<String> words = new ArrayList<>(Arrays.asList("apple", "banana", "kiwi"));
        String longestWord = Collections.max(words, Comparator.comparingInt(String::length));
        System.out.println("Longest word in the list: " + longestWord);
    }
}

Output:

Maximum number in the list: 31
Longest word in the list: banana

Explanation:

In the provided example, we first create a list of integers and determine the maximum number using the max() method. Next, we create a list of strings and determine the longest word by providing a custom comparator to the max() method that compares strings based on their lengths.

Comments