I have a List<Foo>
, and a compare() method taking two Foo objects and returning the 'greater' one. Is there a built-in Java method that takes the list and finds the largest one?
The max() method is an inbuilt method of Math class which is present in java. lang package that is used to find the maximum of two numbers. The max() method takes two inputs that are of types numbers, i.e., int, long, float, double, and returns the maximum of the given numbers.
Stream. max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result.
max() function is an inbuilt function in Java which returns maximum of two numbers. The arguments are taken in int, double, float and long. If a negative and a positive number is passed as argument then the positive result is generated.
Calling stream() method on the list to get a stream of values from the list. Calling mapToInt(value -> value) on the stream to get an Integer Stream. Calling max() method on the stream to get the max value.
If Foo
implements Comparable<Foo>
, then Collections.max(Collection)
is what you're looking for.
If not, you can create a Comparator<Foo>
and use Collections.max(Collection, Comparator)
instead.
// Assuming that Foo implements Comparable<Foo>
List<Foo> fooList = ...;
Foo maximum = Collections.max(fooList);
// Normally Foos are compared by the size of their baz, but now we want to
// find the Foo with the largest gimblefleck.
Foo maxGimble = Collections.max(fooList, new Comparator<Foo>() {
@Override
public int compare(Foo first, Foo second) {
if (first.getGimblefleck() > second.getGimblefleck())
return 1;
else if (first.getGimblefleck() < second.getGimblefleck())
return -1;
return 0;
}
});
Yes, the List is a subclass of Collection and so you can use the max method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With