Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max value in Java with a predefined comparator

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?

like image 906
ripper234 Avatar asked Nov 03 '09 18:11

ripper234


People also ask

How do you find the max value of a function in Java?

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.

How do you find the max element in an Arraylist using a stream?

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.

Is there a max function in Java?

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.

How do you find the maximum number of streams?

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.


2 Answers

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.

Example

// 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;
    }
});
like image 56
Michael Myers Avatar answered Oct 21 '22 03:10

Michael Myers


Yes, the List is a subclass of Collection and so you can use the max method.

like image 40
Ben S Avatar answered Oct 21 '22 04:10

Ben S