Whatman
Whatman

Reputation: 104

Find maximum from multiple double numbers(not an array) in Java?

I have the following values,

    double neutrality = 0.9D;
    double happiness = 0.12D;
    double sadness = 0.232D;
    double anger = 0.001D;
    double fear = 0.43D;

What is the best way to find the maximum value from the above items. I know how to use if..else statements.

Is Math.max() is the best way? like

Math.max(Math.max(Math.max(Math.max(neutrality,happiness),sadness),anger),fear)

Upvotes: 1

Views: 280

Answers (3)

JamesB
JamesB

Reputation: 7894

Add the values to an array and then use:

Collections.max(Arrays.asList(array));

Upvotes: 0

Whatman
Whatman

Reputation: 104

Sample code using 3 ways , using https://repl.it/languages/java

import java.lang.Math;
import java.util.stream.*;
import java.util.*;
class Main {
    public static void main(String[] args) {
        System.out.println("Find max from multiple double numbers(not an array)");

        double neutrality = 0.9D;
        double happiness = 1.12D;
        double sadness = 0.232D;
        double anger = 0.001D;
        double fear = 0.43D;

        System.out.println("The max is: " +
        Math.max(Math.max(Math.max(Math.max(neutrality,happiness),sadness),anger),fear));

        System.out.println("The max is: " +DoubleStream.of(neutrality, happiness, sadness, anger, fear).max().getAsDouble());

        System.out.println("The max is: " +Collections.max(Arrays.asList(neutrality,happiness,sadness,anger,fear)));
    }
} 

Result-

Find max from multiple double numbers(not an array)
The max is: 1.12
The max is: 1.12
The max is: 1.12

Upvotes: 1

Ruslan
Ruslan

Reputation: 6290

Using stream will be more readability:

double max = DoubleStream.of(neutrality, happiness, sadness, anger, fear)
            .max().getAsDouble();

Upvotes: 2

Related Questions