Skip to main content

Stream In Java

stream in java 8 :

Stream API is used to process collection of objects.
stream() method is present in Collection interface from package java.util.
Stream is an interface present in java.util package, filter() and map() methods are present in Stream interface.

-->when to use filter() method ?
If we want to filter elements from collection based on some boolean condition then we can use filter() method. 
for example : filtering even or odd numbers from list of numbers.

-->When to use map() method ?
If we want to create new object for every object in collection then we should use map() method.
for example : if we want to increase every number in list by 2 , here every object is getting modified ,we have to use map() in this type of scenario.

In below example , we used both filter() and map() methods on stream , inside filter method we applied some condition and in map method we are transforming our object to different one.


package com.crtr4u.www;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamDemo1 {
public static void main(String[] args) {
	List<Integer> myList=new ArrayList<Integer>();	
	for(int i=0;i<16;i++)
	{
		myList.add(i);
	}
	System.out.println("Original Numbers List :"+myList);
	List<Integer> evenNumberList=myList.stream().filter(num->num%2==0).collect(Collectors.toList());
	System.out.println("Even numbers filtered from original list : "+evenNumberList);
	List<Integer> processedNumberList=evenNumberList.stream().map(num->num*2).collect(Collectors.toList());
	System.out.println("Processed Even numbers list by multiplying by 2 : "+processedNumberList);	
}
}

Output :
Original Numbers List :[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Even numbers filtered from original list : [0, 2, 4, 6, 8, 10, 12, 14]
Processed Even numbers list by multiplying by 2 : [0, 4, 8, 12, 16, 20, 24, 28]
Lets see one more example with some real time scenarion , follow below steps :
Step 1: Create Student Class as below :

package com.crtr4u.www;
public class Student {
	int id;
	String name;
	String department;
	public Student() {
		super();
	}
	public Student(int id, String name, String department) {
		super();
		this.id = id;
		this.name = name;
		this.department = department;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", department=" + department + "]";
	}
}

Now Write second class as below : in this class we are creating a list of students and then filterting only MCA students using Stream API and displaying them as shown in output :

package com.crtr4u.www;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamDemo2 {
	public static void main(String[] args) {
	List<Student> studentList=
			Arrays.asList(new Student(1,"Swapnil","MCA"),
					new Student(4,"Prashant","Accounting"),
					new Student(3,"Prakash","Mechanical"),
					new Student(2,"Nitesh","MCA"));
	System.out.println("Student List :");
	for(Student student:studentList) {
		System.out.println(student);
	}
	List<Student> filteredMcaStudents=
			studentList.
			stream().
			filter(s->s.getDepartment().equalsIgnoreCase("mca")).
			collect(Collectors.toList());
	System.out.println("filtered MCA students : ");
	for(Student student:filteredMcaStudents) {
		System.out.println(student);
	}	
	}
}

Output : 
Student List :
Student [id=1, name=Swapnil, department=MCA]
Student [id=4, name=Prashant, department=Accounting]
Student [id=3, name=Prakash, department=Mechanical]
Student [id=2, name=Nitesh, department=MCA]
filtered MCA students : 
Student [id=1, name=Swapnil, department=MCA]
Student [id=2, name=Nitesh, department=MCA]
count() in Stream : count() method is present in java.util.stream.Stream interface , the return type of count() method is long, we can use count() method to get the count of objects in filtered list. copy below code in above main class and check :

	long countOfNonMcaStudents = studentList.stream().filter(s->(!s.getDepartment().equalsIgnoreCase("mca"))).count();
	System.out.println("count Of Non Mca Students :"+countOfNonMcaStudents);
	
	long countOfAccountingStudents = studentList.stream().filter(s->s.getDepartment().equalsIgnoreCase("accounting")).count();
	System.out.println("Count of accounting students :"+countOfAccountingStudents);

Output :
count Of Non Mca Students :2
Count of accounting students :1
Now what if i want to change name and department of all students to lower case , check below code and add in above main method and run it , in this code we are using map() method of stream api , to transform objects :

List<Student> processedStudentsData = 
			filteredMcaStudents.
			stream().
			map(s->{
				s.setDepartment(s.getDepartment().toLowerCase());
				s.setName(s.getName().toLowerCase());
				return s;
	}).collect(Collectors.toList());
	System.out.println("Processed MCA Student Data "+processedStudentsData);

Output :
Processed MCA Student Data [Student [id=1, name=swapnil, department=mca], Student [id=2, name=nitesh, department=mca]]

Popular Posts

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Today we will see solution for Error In Spring Boot : ***************************  APPLICATION FAILED TO START ***************************  Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.  Reason: Failed to determine a suitable driver class. --->My Application.yml : server: port: 8081 spring: datasource: driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:xe username: sys as sysdba password: root Oracle Version is 21 C Oracle Database 21c Express Edition Release 21.0.0.0.0 - Production Version 21.3.0.0.0. check my pom.xml here : <? xml version = " 1.0 " encoding = " UTF-8 " ?> < project xmlns = " http://maven.apache.org/POM/4.0.0 " xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance " xsi:schemaLocation = " http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/m...

How much Software Engineer Earn in India

  No limit of earning for free lancer software developer : In service based companies - If Software Engineer work for same MNC from beginning of career then sometimes financial growth is low,still they can reach in between 7 lacs to 15 lacs in India. If programmer switch job after every 2-3 year and work for at least 5 years then they can earn minimum in between 14 lacs to 25 lacs for the position of Senior Software Engineer.  Being from a normal college , completed my education with average percentage , then  As 2 year experienced guy - I was getting offers of 8 lacs, 10 lacs  As 5 years experienced guy the offers are like  Minimum 12 lacs ,14 lacs, 18 lacs from Indian MNCs.  Money is  no bar for right candidate, if you are able to crack interview and if you can  write effective code then you can earn more than 20 lacs in India itself. Be motivated, improve your technical skills and yes you can earn great amount from Job too...  People with ...