JavaScript and JQuery Essentials Trainin... (32 Blogs) Become a Certified Professional
AWS Global Infrastructure

Front End Web Development

Topics Covered
  • AngularJS (9 Blogs)
  • jQuery UI Development (1 Blogs)
  • The Complete WebDeveloper (10 Blogs)
  • ReactJS (7 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Everything You Need To Know About Stream In Java

Published on Jul 31,2019 8 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assement report and video recording

A new additional package in Java 8, known as java.util.stream has been added for the users for an efficient programming experience. A stream can be defined as a sequence of objects, supporting multiple methods. In this article we would be exploring Stream in Java

Following pointers will be Covered in this Article,

Before we get started with this article on Stream In Java, let us take a look at some important features,

Stream In Java: Features

  • A stream is not a data structure and does not store elements. Collections, Arrays or I/O Channels is where it takes the input from.
  • The source of the stream remains unmodified after operations are performed on it. For example, filtering a stream simply produces a new stream without the filtered elements, instead of modifying the original stream.
  • Aggregation operations such as filter, reduce, match, find,  etc are supported by stream.
  • Laziness can be considered as a feature of the stream, as it evaluates the codes only when required.
  • Visitation of the elements present in the stream can only be done once during the lifetime of a stream. A new stream must be created to revisit the same elements present in the source.

Moving on with this article on Stream in Java

Generating Streams

Streams can be generated by the following methods:

  • stream() – A sequential stream is returned. Collection is considered as the source.
  • parallelStream() – A parallel stream is returned. Collection is considered as the source.
List<String> strings = Arrays.asList("Hello", "", "Hi", "Hola", "Bonjour","", "Namaste");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

Moving on with this article on Stream in Java

Operations on Streams:

 Intermediate Operations:

map

The elements present in the collection can be mapped to other objects according to the predicate passed as the argument. The following example is used to display unique squares of the numbers by using the map method.

List<Integer> num = Arrays.asList(5,4,4,2,3,3);
List<Integer> squares = num.stream().map( y -> y*y).distinct().collect(Collectors.toList());

filter

Elements can be removed on the basis of a criteria by using this method.

List name = Arrays.asList("Saturday","Sunday","Thursday");
List res = name.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());

sorted

The stream can be sorted by using this method.

List name = Arrays.asList("Saturday","Sunday","Thursday");
List res = name.stream().sorted().collect(Collectors.toList());

Stream In Java: Terminal Operations:

collect

The result of processing on the elements of a stream can be combined by using the collect operation.

List num = Arrays.asList(4,3,2,5,6);
Set res = num.stream().map(y->y*y).collect(Collectors.toSet());

forEach

This method is used for iterating through every element present in the stream.

List num = Arrays.asList(4,3,2,5);
num.stream().map(x->x*x).forEach(y->System.out.println(y));

reduce

The elements of the stream can be reduced to a single value by using this method.

List num = Arrays.asList(4,3,2,5);
int even = num.stream().filter(x->x%2==0).reduce(0,(res,i)-> res+i);

The variable res is assigned the value 0 initially, and i is added to it.

Moving on with this article on Stream in Java 

Filtering

The code can be filtered by using the stream method. In the following example, the price of the instruments gets filtered out.

import java.util.*;
import java.util.stream.Collectors;
class Instrument{
int num;
String name;
float price;
public Instrument(int num, String name, float price) {
this.num = num;
this.name = name;
this.price = price;
}
}
public class Test {
public static void main(String[] args) {
List<Instrument> instrumentsList = new ArrayList<Instrument>();
//Adding Products
instrumentsList.add(new Instrument(1,"Guitar",15000f));
instrumentsList.add(new Instrument(2,"Piano",18000f));
instrumentsList.add(new Instrument(3,"Flute",15000f));
instrumentsList.add(new Instrument(4,"Drums",48000f));
instrumentsList.add(new Instrument(5," Ukulele",32000f));
List<Float> InstrumentPriceList2 =instrumentsList.stream()
.filter(p -> p.price > 30000)// filtering data
.map(p->p.price)//fetching price
.collect(Collectors.toList()); // collecting as list
System.out.println(InstrumentPriceList2);
}
}
Output:

[48000.0, 32000.0]

Moving on with this article on Stream in Java

 Iterating:

Iteration can be performed by using stream in java.

import java.util.stream.*;
public class Test {
public static void main(String[] args){
Stream.iterate(1, element->element+1)
.filter(element->element%4==0)
.limit(6)
.forEach(System.out::println);
}
}

Output:

4

8

12

16

20

24

Let’s take a look at another example, to understand the concept of Stream in java more effectively.

Example:

import java.util.*;
import java.util.stream.*;
public class Test
{
public static void main(String args[])
{
//creating a list of integers
List<Integer> num = Arrays.asList(6,7,8,9);
//using map method
List<Integer> squares = num.stream().map(y -> y*y).
collect(Collectors.toList());
System.out.println(squares);
//creating a list of String
List<String> days =
Arrays.asList("Friday","Saturday","Sunday");
//filter method
List<String> res = days.stream().filter(s->s.startsWith("S")).
collect(Collectors.toList());
System.out.println(res);
//sorted method
List<String> display =
days.stream().sorted().collect(Collectors.toList());
System.out.println(display);
//creating a list of integers
List<Integer> number = Arrays.asList(6,9,5,7,1);
//collect method returns a set
Set<Integer> sqSet =
number.stream().map(y->y*y).collect(Collectors.toSet());
System.out.println(sqSet);
//forEach method
num.stream().map(y->y*y).forEach(x->System.out.println(x));
//reduce method
int even =
num.stream().filter(x->x%2==0).reduce(0,(result,i)-> result+i);
System.out.println(even);
}
}

Output:

[36, 49, 64, 81]

[Saturday, Sunday]

[Friday, Saturday, Sunday]

[81, 49, 1, 36, 25]

36

49

64

81

14

Streams enable the user to perform operations on the elements effectually.

Thus we have come to an end of this article on ‘Stream in Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog  and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.