You can do this without Guava.
Collections provides min
and max
methods that operate on any Collection, including overloads taking comparators. Here we use the Java 8 Comparator static methods with a lambda to concisely specify a comparator, but before Java 8 you can use an anonymous class:
Item max = Collections.max(list, Comparator.comparingInt(i -> i.price));
These methods will throw NoSuchElementException if the collection is empty.
Java 8 streams provide min
and max
functions taking a comparator. These functions return Optional<T>
to gracefully handle the stream being empty. The static methods in Comparator are useful for concisely specifying comparators, including the common case of the natural ordering. For this question, you'd use
Optional<Item> max = list.stream().max(Comparator.comparingInt(i -> i.price));
This will work for any stream source, which includes all Collection implementations, as well as other things like files, and makes it easy to compute the max of a subset of a collection by filtering the stream. If you have a large collection and an expensive comparator (e.g., String's natural ordering), you can use a parallel stream.
(Aside: ideally Stream would provide min
and max
overloads taking no argument when the stream type implements Comparable. Unfortunately Java doesn't support conditionally exposing methods based on a type parameter, and it isn't worth introducing a new StreamOfComparable interface extending Stream just for this case.)