Everything You Need To Know About Stream In Java

Last updated on Jun 21,2023 2.3K Views

Everything You Need To Know About Stream In Java

edureka.co

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

Moving on with this article on Stream in Java

Generating Streams

Streams can be generated by the following methods:

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.

Check out the Angular Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Angular is a JavaScript framework that is used to create scalable, enterprise, and performance client-side web applications. With Angular framework adoption being high, performance management of the application is community-driven indirectly driving better job opportunities.

If you want to get trained in React and wish to develop interesting UI’s on your own, then check out the React Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

https://www.edureka.co/reactjs-redux-certification-training

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.

Upcoming Batches For Angular Certification Training Course Online
Course NameDateDetails
Angular Certification Training Course Online

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Angular Certification Training Course Online

Class Starts on 15th February,2025

15th February

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES