Array To Stream in Java


With Java 8, Arrays class has a stream() methods to generate a Stream using the passed array as its source.

Description

The java.util.Arrays.stream() method returns a sequential Stream with the specified array as its source. −

Arrays.stream(array)

Declaration

Following is the declaration for java.util.Arrays.stream() method

public static <T> Stream<T> stream(T[] array)

Type Parameter

  • T − This is the type of the array elements.

Parameter

  • array − This is the source array to be used.

Return Value

This method returns a stream for the array.

Example

The following example shows the usage of java.util.Arrays.stream() method.

Live Demo

import java.util.Arrays;

public class Tester {
   public static void main(String args[]) {
      int data[] = { 1, 2, 3, 4, 5 };

      //iterative way to compute sum and average of an array
      int sum = 0;

      for(int i = 0; i< data.length; i++) {
         sum+= data[i];
      }

      System.out.println("Sum : " + sum);
      System.out.println("Average : " + sum/data.length);

      //declarative way to compute sum and average of an array
      sum = Arrays.stream(data).sum();

      System.out.println("Sum : " + sum);
      System.out.println("Average : " + sum/data.length);
   }
}

Output

Compile and Run the file to verify the result.

Sum : 15
Average : 3
Sum : 15
Average : 3

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 18-Jun-2020

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements