~/ learn/ java-from-zero/ cards/ Bounded type parameters: extends and multiple bounds
1 of 4

Type a generic method with a Comparable upper bound

Type a generic method with a Comparable upper bound

Answer

public static <T extends Comparable<T>> T max(List<T> xs) { return xs.stream().max(Comparator.naturalOrder()).orElseThrow(); }

<T extends Comparable<T>> means T must implement Comparable<T>. The bound unlocks compareTo and lets us express ordering constraints.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e17f6566-5fd0-4dc0-a6b0-8b23459362fb/flashcard utf-8 LF