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
| Parameter | Type | Description |
|---|---|---|
| coll | Collection<? extends T> | A non-empty collection. |
| comp | Comparator<? 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
bananaNotes
An empty collection throws NoSuchElementException. If the collection may be empty, stream().max(...) is handier because it returns an Optional.
See also
- Collections.min() — Finds the smallest element of a collection.
- Stream.max() — Finds the largest element of a stream.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
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.