Stream API🍵
By Debarjit Mohanty
Stream API
Collection: A Group of Objects as a single Entity, It means a single unit of objects.
Stream: If we want to process the object from a collection, then we should use a Stream.
Package: java. util. stream
Collection to Stream: Stream S = collection. stream();
In Stream API, operations are classified into two operation:
1. Intermediate Operations:
Transform a stream into another stream.
Examples are: filter, map, distinct, sorted, limit etc.
2. Terminal Operations:
It produce a result and terminate the stream
Examples are: forEach, collect, reduce, count etc.
Stream API Methods
• stream()
• filter()
• map()
• collect()
• count()
• sorted()
• max() and min()
• forEach()
• toArray()
• Arrays. stream()
• Stream. of()
Filter:
Syntax: Stream filteredStream = [Link](element->/*predicate */);
• It is used to filter the data from stream.
• And create a new stream.
• filter takes predicate as an argument, which returns Boolean types (true/false)
• It is intermediate operation.
Q: Find the even number from ArrayList using stream.
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<Integer> list=[Link](1,2,3,4,5,6);
//List<Integer> result = [Link]().filter(i->i%2==0).collect([Link]());
List<Integer> result = [Link]().filter(i->i%2==0).toList();
[Link](result);
}
}
Map
Syntax: Stream mappedStream = [Link](element->/*transformation function */);
• Map is used to transform each element of Stream.
• And returns a new Stream
• Map takes function as an argument, the return type based on the types of data.
• It is intermediate operation.
Q: Multiply by two for each element from the list.
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<Integer> list=[Link](1,2,3,4,5,6);
List<Integer> result = [Link]().map(i->i*2).toList();
[Link](result);
}
}
Q: Select only passed student.
Q: Add the 5 grace marks to all the failed student.
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<Integer> mark=[Link](40,35,65,19,75,85,30,24,47);
List<Integer> passed = [Link]().filter(i->i>35).toList();
[Link](passed);
List<Integer> graceMark = [Link]().filter(i->i<=35).map(i->i+5).toList();
[Link](graceMark);
}
}
count():
To count the number of elements in the Stream
Q: Get the total number of failed students.
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<Integer> mark=[Link](40,35,65,19,75,85,30,24,47);
long failed_std = [Link]().filter(i-> i<35).count();
[Link](failed_std);
}
}
sorted():
To sort the order of elements in the Stream.
- Sorted according to natural order.(Asc)
Q: Sort the element from stream.
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<Integer> mark=[Link](40,35,65,19,75,85,30,24,47);
List<Integer> sorted_mark = [Link]().sorted().toList();
[Link](sorted_mark);
List<String> name=[Link]("rajesh", "hemant", "debarjit", "srinivas");
List<String> name_sort = [Link]().sorted().toList() ;
[Link](name_sort);
}
}
If we want sort in descending order, then how to perform?
if we want customize sorting order then we should go for Comparator.
• comparator is a Functional Interface.
• It has compare(obj1, obj2) method.
return -ve; if obj1 has come before obj2.
return +ve; if obj1 has come after obj2.
return 0; if obj1 and obj2 are equal
For Descending Order: ( a , b ) -> (a < b) ? 1 : ( a > b ) ? -1 : 0
➢ sorted(): According to default natural sorting order
➢ sorted d(Comparator): For customized sorting order
Q: Sort the element in descending order using comparator from stream.
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<Integer> mark=[Link](40,35,65,19,75,85,30,24,47);
// List<Integer> sorted_mark = [Link]().sorted((a,b)->(a<b)?1:(a>b)?-1:0).toList();
List<Integer> sorted_mark = [Link]().sorted((a,b)->[Link](a)).toList();
[Link](sorted_mark);
}
}
Comparable
Method: compareTo(obj1):
[Link]( ).sorted( ( a , b ) -> [Link]( b ) ) . toList( );
If want to reverse the sorting then put the "-" symbol as below
[Link]( ).sorted (( a , b) -> -[Link](b)). toList();
Q: Sort the element based on the length of the ArrayList
1st way
import [Link];
import [Link];
import [Link];
public class ClassDemo {
public static void main(String[] args) {
List<String> list = [Link]("A", "AAA", "BB", "BBBBB", "AAAAAA");
List<String> result = [Link]().sorted().toList(); //sort in alphabetical order
Comparator<String> c = (a, b) -> {
int l1 = [Link]();
int l2 = [Link]();
/* if (l1 < l2) return -1;
else if ( l1 > l2 ) return 1;
else return 0; */ // one way using if_else
return [Link]( l1 , l2 ); //second way
};
List<String> sortedString = [Link]().sorted(c).toList(); //sort in length wise
[Link](sortedString);
}
}
2nd way
Comparator<String> c = (a, b) -> {
int l1 = [Link]();
int l2 = [Link]();
return [Link]( l1, l2 );
};
//List<String> sortedString = [Link]().sorted((a,b)->[Link]([Link](),[Link]())).toList(); //one way
List<String> sortedString = [Link]().sorted([Link](String :: length)). toList(); //second way
[Link](sortedString);
Q. Sort the element based on the length of the ArrayList in reverse order
Comparator<String> c = (a, b) -> {
int l1 = [Link]();
int l2 = [Link]();
return [Link]( l2, l1 ); //only modify this line remaining same
};
List<String> sortedString = [Link]().sorted(c). toList();
[Link](sortedString);
min( ) & max( ):
• Both method takes the comparator as an argument.
• And based on the comparator result it will return the value.
➢ min (comparator) will return 1st element from the comparator result;
➢ max (comparator) will return last element from the comparator result;
List<Integer> list = [Link](10,20,50,54,12,11,94);
Integer min = [Link]().min((a,b)->[Link](a,b)).get();
Integer max= [Link]().max((a,b)->[Link](a,b)).get();
[Link](min+”\n”+max);
List<String> list = [Link]("A", "AAA", "BB", "BBBBB", "AAAAAA");
Comparator<String> c = (a, b) -> {
int l1 = [Link]();
int l2 = [Link]();
return [Link]( l1, l2 );
};
String min = [Link]().min(c).get();
String max = [Link]().max(c).get();
[Link](sortedString);
forEach():
• То perform an action for each element of this stream
• It is terminal operation.
• It’s similar to for loop
List<Integer> list = [Link](10,20,50,54,12,11,94);
[Link]().forEach(i->[Link](i)); //one way
[Link]([Link]::println); //second way
toArray():
• It returns an array containing elements of this stream.
• It is a terminal operation.
Q: How to convert Stream of object into Array?
Integer[ ] i=list. stream ( ). toArray (Integer[ ]::new);
Q: How to convert Array to Stream?
Arrays. stream (array) or Stream. of (arr)
Integer[ ] arr={10,20,30,40,50};
[Link](arr);
Q: How to find even no from an Array ?
Integer[ ] arr={10,20,30,40,50};
[Link](arr).filter(i->i%2==0).forEach([Link]::println);
Stream. of (args):
Arguments should be any type either arrays or any group of elements
Stream<?> items=[Link](9 ,44, “aaa”, 46, “bb”, 56);
[Link]([Link]::println);
Interview Questions
Q: Find the employee who has maximum salary?
Q: Find the employee whose has secônd highest salary?
Q: Find the employee who is most senior based on joining date?
Q: Count the employee based on the gender?
[Link]
package com.pack1;
import [Link];
public class Employee {
private String name;
private double salary;
private Date joiningdate;
private String gender;
public Employee(String name, double salary, Date joiningdate, String gender) {
super();
[Link] = name;
[Link] = salary;
[Link] = joiningdate;
[Link] = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
[Link] = salary;
}
public Date getJoiningdate() {
return joiningdate;
}
public void setJoiningdate(Date joiningdate) {
[Link] = joiningdate;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
[Link] = gender;
}
@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + ", joiningdate=" + joiningdate + ", gender=" +
gender+ "]";
}
}
[Link]
package com.pack1;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class testEmp {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date joiningDateDev = [Link]("01-01-2022");
Date joiningDateSrinivas = [Link]("15-04-2023");
Date joiningDateKavya = [Link]("25-12-2023");
Date joiningDatePriya = [Link]("08-09-202022");
List<Employee> emp = [Link](new Employee("Dev", 20000, joiningDateDev, "M"),
new Employee("Srinivas", 15000, joiningDateSrinivas, "M"),
new Employee("Kavya", 15000, joiningDateKavya, "F"),
new Employee("Priya", 18000, joiningDatePriya, "F")
);
// Find the employee who has maximum salary?
// Employee maxSalary = [Link]().max((a, b) ->
[Link]([Link](), [Link]())).get(); //one way
Employee maxSalary1 = [Link]().
max([Link](Employee::getSalary)).get();
[Link](maxSalary1);
// Find the employee whose has secônd highest salary?
Optional<Employee> secMaxSal = [Link]().
sorted((a, b) -> [Link]([Link](), [Link]()))
.skip(1).findFirst();
[Link](secMaxSal);
// Find the employee who is most senior based on joining date?
Optional<Employee> senior = [Link]()
.min((a, b) -> [Link]().compareTo([Link]()));
[Link](senior);
// Count the employee based on the gender?
Map<String, Long> gender = [Link]()
.collect([Link](Employee::getGender, [Link]()));
[Link](gender);
}
}