Comparing more than 2 doubles at the same time

37 views Asked by At

How do you compare multiple doubles and return a value to see which one is the biggest? I have 4 doubles that I'm trying to compare on the same line and Double.compare only accepts 2 parameters.

I think I have a pretty good understanding on how to compare 2, but I can't figure out how to do more than 2 at once.

1

There are 1 answers

0
Christoph Dahlen On

If you are just interested in the maximum (or minimum), this method "maxOfList" might serve as a template:

import java.util.List;

public class Clazz {

    // actual logic
    public static Double maxOfList(final List<Double> doubles) {
        return doubles.stream().max(Double::compareTo).get();
    }

    public static void main(String[] args) {

        // sample data
        var doubles = List.of(Math.random(), Math.random(), Math.random(), Math.random());

        // sample usage
        System.out.println("doubles: " + doubles);
        System.out.println("max:     " + maxOfList(doubles));
    }

}