How to use average in IntStream?

Here is an example to explain how to use average() in IntStream.

Syntax:

Modifier and Type         Method
OptionalDouble            average()
package com.nourit.java8.Streams.IntStream;

import java.util.OptionalDouble;
import java.util.stream.IntStream;

public class IntStreamAverage {

  public static void main(String[] args) {
    System.out.println("---------- Average Example -----------------");
    IntStream intStream = IntStream.of(0, 1, 2, 3, 4, 5, 6);
    // returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty
    OptionalDouble d = intStream.average();
      if(d.isPresent()){
        System.out.println(d.getAsDouble());
      }else{
        System.out.println("Empty...");  
      }    
    
    System.out.println("---------------------------------------");
  }
}

Output:

---------- Average Example -----------------
3.0
---------------------------------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*