Sunday, 15 July 2018

Java8: Arrays.stream example: Get the stream from an array

'java.util.Arrays' class provides 'stream' method, it takes an array as input and returns the stream as output.

public static <T> Stream<T> stream(T[] array)
public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive)
public static IntStream stream(int[] array)
public static IntStream stream(int[] array, int startInclusive, int endExclusive)
public static LongStream stream(long[] array)
public static LongStream stream(long[] array, int startInclusive, int endExclusive)
public static DoubleStream stream(double[] array)
public static DoubleStream stream(double[] array, int startInclusive, int endExclusive)

startInclusive: Specifies the first index to cover, inclusive
endExclusive: Specifies the index immediately past the last index to cover



Example
/* Define Employee array */
Employee[] empsArray = { emp1, emp2, emp3, emp4, emp5 };

/* Create stream from empsArray */
Stream<Employee> empsStream = Arrays.stream(empsArray);

/* Add all the employees information from stream to employees list */
empsStream.forEach(employees::add);

Find the below working application.

Test.java
package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import com.sample.app.model.Employee;

public class Test {

 private static List<Employee> employees = new ArrayList<>();

 private static void printEmployees(List<Employee> emps) {
  emps.stream().forEach(System.out::println);
 }

 public static void main(String args[]) {
  Employee emp1 = new Employee(1, "Krishna", "Gurram");
  Employee emp2 = new Employee(2, "Joel", "Chelli");
  Employee emp3 = new Employee(3, "Gopi", "Battu");
  Employee emp4 = new Employee(4, "Janaki", "Sriram");
  Employee emp5 = new Employee(5, "Janaki", "Maj");

  /* Define Employee array */
  Employee[] empsArray = { emp1, emp2, emp3, emp4, emp5 };

  /* Create stream from empsArray */
  Stream<Employee> empsStream = Arrays.stream(empsArray);

  /* Add all the employees information from stream to employees list */
  empsStream.forEach(employees::add);

  /* Print list of employees */
  printEmployees(employees);

 }
}


Run Test.java, you can able to see below messages in console.
Employee [id=1, firstName=Krishna, lastName=Gurram]
Employee [id=2, firstName=Joel, lastName=Chelli]
Employee [id=3, firstName=Gopi, lastName=Battu]
Employee [id=4, firstName=Janaki, lastName=Sriram]
Employee [id=5, firstName=Janaki, lastName=Maj]




Previous                                                 Next                                                 Home

No comments:

Post a Comment