Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collections.max()

Finds the largest element of a collection.

Available since: Java 1.2

Syntax

static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)
static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)

Parameters

ParameterTypeDescription
collCollection<? extends T>A non-empty collection.
compComparator<? super T>Optional comparison rule.

Return value

TThe largest element.

Examples

The maximum number and the longest string:

void main() {
    IO.println(Collections.max(List.of(4, 17, 9)));
    List<String> words = List.of("fig", "banana", "kiwi");
    IO.println(Collections.max(words, Comparator.comparing(String::length)));
}

Output:

17
banana

Notes

An empty collection throws NoSuchElementException. If the collection may be empty, stream().max(...) is handier because it returns an Optional.

See also

Related recipes

In the tutorial

  • Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.

Thanks for reading!

Donate to the site — we work hard for you.