-3

Consider I have this method which take multiple parameters, and I want to make some simple calculation like count, sum, average, min, max, Take a look at this native example :

public static void calculate(int... param) {
    int sum = 0;
    for (int i : param) {
        sum += i;
    }
    System.out.println(sum);
}

How can I pass this parameters (int... param) in a Java-8 Stream and make this calculation?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

3 Answers3

10

If you want to do multiple checks on these params and only use one stream have a look at IntStream.summaryStatistics()

This will allow you to do this

IntSummaryStatistics statistics = IntStream.of(param).summaryStatistics();

statistics.getAverage();
statistics.getMax();
statistics.getMin();
statistics.getSum();
statistics.getCount();

IntSummaryStatistics is a very useful class for getting multiple statistics out of a stream.

Ash
  • 2,562
  • 11
  • 31
6

You can use Array.stream like this :

//pass your method parameters in stream like this 
Arrays.stream(param).sum();
//--------------^---------

Here are some simple calculations:

public static void calculate(int... param) {
    //calculate sum
    Arrays.stream(param).sum();

    //calculate average
    Arrays.stream(param).average().getAsDouble();

    //count number of paramettres
    Arrays.stream(param).count();

    //find maximum
    Arrays.stream(param).max();

    //find minimum
    Arrays.stream(param).min();

    //find the first element
    Arrays.stream(param).sorted().findFirst();
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
5

Also possible: IntStream.of(param).sum();

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
kamehl23
  • 522
  • 3
  • 6