Why not Math.max (double a, double b) variadic?

Why is not the implementation of Math.max a variational function ?

It can be implemented as follows:

public class Main {
    public static double max(double... values) {
        double max = Double.NEGATIVE_INFINITY;
        for (double tmp : values) {
            max = max < tmp ? tmp : max;
        }
        return max;
    }

    public static void main(String[] args) {
        // This works fine:
        System.out.println(max(-13, 12, 1337, 9));

        // This doesn't work:
        // System.out.println(Math.max(-13, 12, 1337));
    }
}

Is there a reason this is not implemented?

+5
source share
6 answers

While others have already answered why Math.maxit is not a variable, they have not answered why such a method is not created when introducing variational functions.

I don’t even know this (there is an open error report ), so I can only guess:

It is true that it is not implemented in Math, but if we look at it Collections, there will be the following method:

public static <T extends Object & Comparable<? super T>> T max(
    Collection<? extends T> coll) {
  ...
}

( ), Collections.max(Arrays.asList(-13, 12, 1337, 9)); , , .

: , , Comparable.

, , Collections -, . JDK8 :

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

int max(List<Integer> list) {
  Optional<Integer> opt = list.stream().max((a,b) -> a-b);
  return opt.orElse(Integer.MAX_VALUE);
}

max(Arrays.asList(-13, 12, 1337, 9)); // 1337
max(Arrays.asList()); // 2147483647

Project Lambda, . Lambdas . :

import static java.util.Comparators.naturalOrder;

Arrays.asList(-13, 12, 1337, 9)
  .stream()
  .max(naturalOrder())
  .ifPresent(System.out::println); // 1337

max reduce:

Arrays.asList(-13, 12, 1337, 9)
  .stream()
  .reduce((a,b) -> a > b ? a : b)
  .ifPresent(System.out::println); // 1337

- Optional. - , .

, Math.max:

  • -
  • . , (List, Set, Stream, Iterator ..)
  • .
  • . .stream() .parallelStream()
+3

java.lang.Math JDK 1.0 , Java 5.

, : , "inline", . .

+5

, , java ( java 5), , , .

, varargs, (double [])

+2

Java 8 , . :

DoubleStream.of( -13, 12, 1337, 9 ).max().getAsDouble()

, , , .

, :

stream.parallel().max().getAsDouble()

, max - , . , .

min, average, sum .. , :

DoubleSummaryStatistics stat = DoubleStream.of( -13, 12, 1337, 9 ).summaryStatistics();
System.out.println( stat.getMin() );
System.out.println( stat.getAverage() );
System.out.println( stat.getMax() );
System.out.println( stat.getCount() );
System.out.println( stat.getSum() );
+2

Math.max JDK 1.0 , #. , , . , . , .

Max , var args . , , , , Math. , . , , , .

, Java n Java n + 1, . , java.sql.Connection Java 6 Java 7, Java 7 AutoCloseable. Java 9 , jigsaw.

I can not think of why Math.max is not updated. Maybe no one has suggested this until now. Are you reading this, Mark Reinhold ?

+1
source

Math.max() goes back to JDK 1.0, while variational functions did not exist before Java 5.

0
source

All Articles