1

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)
Whatman
  • 104
  • 6
  • 1
    Possible duplicate of [Find the max of 3 numbers in Java with different data types](https://stackoverflow.com/questions/4982210/find-the-max-of-3-numbers-in-java-with-different-data-types) – Ivar May 02 '19 at 21:38
  • In addition to plain Java, it is worth noting that Apache’s NumberUtils provides a max function https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html , so can have ‘result = max(neutrality, happiness, sadness, anger, fear)’ – racraman May 02 '19 at 22:15

3 Answers3

2

Using stream will be more readability:

double max = DoubleStream.of(neutrality, happiness, sadness, anger, fear)
            .max().getAsDouble();
Ruslan
  • 6,090
  • 1
  • 21
  • 36
1

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
Whatman
  • 104
  • 6
0

Add the values to an array and then use:

Collections.max(Arrays.asList(array));
JamesB
  • 7,774
  • 2
  • 22
  • 21