SEARCH BY

All

  • All
  • Java8
  • Spring

Streams in java8

Post a Comment

Introduction

In this article iam sharing an examples for using one of the great feature of Java8 that is Stream. Streams are very useful concept in/from java8 to apply actions on the data by taking data from different sources like Collections and Arrays.
Stream never holds data, it collects data from Collections or Arrays and convert it into Stream, where we can apply intermediate methods and terminal methods to perform required operations.
Stream Pipeline is the mechanism where we can apply sequence of intermediate methods on Steam retrieved from Collection or Arrays.
SQL like operations on data can be performed with Streams API from java-8

Creating Streams

There are different ways to create Streams

Creating Stream by passing values directly to Stream.of() method

We can create Streams to non primitive types only
Following is the example for Converting Integer values into Integer Stream
// Following line creates Stream of employee ages 
Stream<Integer> empAges=Stream.of(23,45,56,78);
// Here we are using forEach() method to display ages of Stream
empAges.forEach(age->System.out.println("Age:"+age));

Creating Stream from Array by using Stream.of() method

//Here we are creating a Stream from an Integer array which holds employee ages
Stream<Integer> empAges= Stream.of(new Integer[]{34,56,32,23});
//we are using forEach() method to iterate Stream elements

Creating Stream from List or Collections by using stream() method

As said Stream can get the data from either collections or arrays. In the above we have seen that how to create Stream from Arrays. Now we will see how to create Stream from Collection object.
We can call stream() method on Collection object to create stream.

// creating List object of employees
List<Employee> empList= Employee.getEmployessSamples();
// Now we invoke stream() method on empList object to create Stream
empList.stream();

Convert Stream to list ( Creating List from stream ) by using collect(Collectors.toList()) method 


// In this example we try to get new list of employees whose name starts with letter j

// To get the list of employees whose name starts with j we can use filter() method of Stream

List<Employee> empList=  Employee.getEmployessSamples();
// now we are converting the empList into Stream first

Stream<Employee> empStream=empList.stream();

// now we are applying filter method on stream to get employees name starts with letter j

empStream.filter(emp
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox