SlideShare a Scribd company logo
JAVA 8 STREAMS
Zameer Ahmed Shaik.
Senior Full Stack Java Engineer.
• Introduction
• Processing Collections - Java7 Vs Java8
• Introducing Java8 Stream APIs.
• Basic operations using Streams
• Advanced operations.
• Parallel stream.
• Read Stream of Lines from a File.
In This Tutorial ..
• Java Stream is an abstraction that lets you process data in a
declarative way.
• Perform SQL like operations on Collections.
• process really large collections efficiently By leverage Multi core
architectures.
What is Stream ?
Processing Collections - Java7 Vs Java8
• Find the list of employee ids sorted based on their Salary in a given
city.
List<Employee> employeeList =
StreamDemoHelper.getEmployeeList();
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
Each row in the above table represents Employee
Object.
List<Employee> employeeList = StreamDemoHelper.getEmployeeList(
List<Employee> melboureEmployees = new ArrayList<>();
for(Employee emp : employeeList){
if(emp.getCity().equals("MEL")){
melboureEmployees.add(emp);
}
}
Collections.sort(melboureEmployees, new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
return o2.getSalary().compareTo(o1.getSalary());
}
});
List<Long> melEmpIdList = new ArrayList<>();
for(Employee emp : melboureEmployees){
melEmpIdList.add(emp.getEmployeeId());
}
Processing Collections - Java7
1. Iterate the list of Employees
and check each employees
city and add it to a separate
list.
2. Sort the list of Employees in
Melbourne based on salary.
3. Iterate Melbourne
employees and then add it
to separate list of ids.
Output: [1, 4, 3]
List<Long> empIds =
employeeList.stream()
.filter(emp -> emp.getCity().equals("MEL"))
.sorted(comparing(Employee::getSalary)
.reversed())
.map(emp -> emp.getEmployeeId())
.collect(toList());
Processing Collections – Java8
Only Declare what need to
be performed using Steam
APIs.
This code will produce the
same result as that of
previous code.
Don’t worry if you don’t
understand, we will see all the
Stream APIs in the next slides.
stream() filter() sorted() collect()
toList() toMap() toSet() sum()
count() avaragingInt() map()
averagingLong()
averagingDouble() groupingBy()
reduce() minBy() maxBy() limit()
skip() allMatch() findAll() findAny()
partitioningBy() flatMap() joining()
mapping() collecting()
Java8 Stream APIs
1. Filter Employees based on city.
2. Total number of people whose salary greater than $230
3. Find List of Employee ids whose salary is less than $250 of a given
city.
4. Distinct Cities in which employees has salaries less than $250
5. Find total amount of money spent on Salaries Every Month.
6. Other operations..
Basic operations using Streams
Filter Employees based on city.
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
EMP ID City Salary
1 MEL 250
3 MEL 150
4 MEL 200
List<Employee> melEmpList = employeeList.stream()
.filter(emp -> emp.getCity().equals("MEL"))
.collect(Collectors.toList());
filter() method takes lamda expression of
Predicate type and filters the stream based on
the condition defined.
collect() method collects the filtered Steam objects
and converts it to List of Employee objects using
Collectors.toList() method defined inside it.
Collectors class has toSet(), toMap(), toConcurrentMap(), toCollection() methods to convert
the stream of objects to a particular type of collection.
Total number of people whose salary greater than $230
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
Long count = employeeList.stream()
.filter(emp -> emp.getSalary() > 230)
.count();
Filter employees whose salary is greater than
$250
count() will return the total of the filtered items.
count = 3
Find List of Employee ids whose salary is less than $250 of a
given city.
List<Long> melEmpIds = employeeList.stream()
.filter(emp -> emp.getCity().equals("MEL")
&& emp.getSalary() < 250)
.map(emp -> emp.getEmployeeId())
.collect(toList());
filter method actually return stream of employee
objects which is Stream<Employee>.
map() functions comes to our rescue to create a
stream of whatever we want based on the
employee object. map() function returns stream
of whatever that is returned in the lamda
expression that is passed to it. In our case map()
function returns Stream of employee ids.
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
EMP ID City Salary
1 MEL 250
3 MEL 150
4 MEL 200
[3, 4]
filter()
map()
some more examples of map() function…
List<Bonus> bonusList = employeeList.stream()
.map(emp -> new Bonus(emp.getEmployeeId(),
emp.getSalary() * 1.5))
.collect(toList());
The Lamda expression of map() function
returns Bonus object based on Employee
object and hence we get Stream of Bonus
objects which is Stream<Bonus>
whoAmI = employeeList.stream()
.map(emp -> {
Integer tax =calculateTaxes(emp);
//Date date = get payroll date.
return new Payroll(emp.getEmpId,
emp.geSalary,
date,
tax);
})
.collect(toList());
Guess what is the type of whoAmI ?
It is List<Payroll>
Find total amount of money spent on Salaries Every Month.
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
Long sumOfSalaries = employeeList.stream()
.mapToLong(emp -> emp.getSalary())
.sum();
sum() will return the total of all the salaries.
}Total = 1680
mapToLong() is similar to map() function except
map() returns Stream<Object> whereas
maptoLong returns LongStream object and helps
us perform sum() of all the Longs. Similarly, we have mapToInt() &
mapToDouble() to be used with
Integer and Double.
Distinct Cities in which employees has salaries less than $250
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
List<String> distinctCities =
employeeList.stream()
.filter(emp -> emp.getSalary() < 250)
.map(emp -> emp.getCity())
.distinct()
.collect(toList());
First filtering employees whose salary is less
than $300
distinct() method basically removes all the
duplicates.
MEL
MEL
SYD
SYD
filter()
[MEL,
SYD]
distinct()
Other Operations..
Check whether all the employees have salary
greater than $75. In this case it will return true.
Boolean allMatch = employeeList.stream()
.allMatch(emp -> emp.getSalary() > 75);
Double averageLong = employeeList.stream()
.collect(averagingLong(Employee::getSalary));
Highest & Lowest salaried employees.
Average salary in the company
Optional<Employee> minSalariedEmployee =
employeeList.stream()
.collect(minBy(comparing(Employee::getSalary)));
For maximum salaried employee use maxBy() function of Collectors class.
Please check Collectors method for other functions like reducing(), joining(), mapping() etc.
1. Group employees based on whether salary greater than $250
2. Group employees based on City and order by Salary
3. Group employees based on city and then group each city by the
role of the employee and order by salary.
Advance operations using Streams
1. Group employees based on whether salary greater than
$250
Map<Boolean , List<Employee> > partitionByMap =
employeeList.stream()
.collect(Collectors.partitioningBy(emp ->
emp.getSalary() > 250));
partitioningBy() method groups the collection
based on the codition passed to it. In this case
employees are grouped based on whether their
salary is greater than $250.
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
true [emp6, emp5]
false [emp1, emp3, emp2, emp7, emp4]
Map<Boolean, List<Employee>>
List<Employee>
Group employees based on City whose salary > 150 and order
by Salary
Map<String, List<Employee>> groupByCity =
employeeList.stream()
.filter(emp -> emp.getSalary() > 150)
.sorted(comparing(Employee::getSalary).reversed())
.collect(Collectors.groupingBy(emp -> emp.getCity()));
Collectors.groupingBy() is used to group the
collection based on the return type of the lamda
defined in it. In this case we are grouping based
on the City.
Just Note that in this case , grouping happens on
the filtered and sorted collection which we passed
to the collect method.
EMP ID City Salary
1 MEL 250
3 MEL 150
2 SYD 230
6 BRS 400
5 SYD 350
7 SYD 100
4 MEL 200
BRS [emp6]
MEL [emp1, emp4]
SYD [emp5, emp2]
Map<String, List<Employee>>
List<Employee>
Id=1
$250, MEL
Id=3
$150,MEL
Id=2
$230,SYD
Id=6
$400,BRS
Id=5
$350,SYD
Id=7
$100,SYD
Id=4
$200,MEL
Id=1
$250, MEL
Id=2
$230,SYD
Id=6
$400,BRS
Id=5
$350,SYD
Id=4
$200,MEL
Id=6 Id=2
$230, SYD
Id=4
$200,MEL
Java 8 Streams – Filter, Sort on Salary & Group by City
.filter(e ->
e.getsalary >
150)
empList.stream()
.sorted(
comparing(
e -> e.getPrice))
$400,BRS
Id=5
$350,SYD
Id=1
$250, MEL
groupingBy(
emp -> emp.getCity)
Id=6
$400,BRS
Id=5
$350,SYD
Id=2
$230, SYD
Id=1
$250, MEL
Id=4
$200,MEL
BRS SYD MEL
..continued
Group employees based on city and then group each city by
the role of the employee and order by salary.
Map<String, Map<String, List<Employee>>>
groupByCityAndRole = employeeList.stream()
.sorted(comparing(Employee::getSalary).reversed())
.collect(groupingBy(emp -> emp.getCity(),
groupingBy(emp -> emp.getRole())));
Collectors.groupingBy() overloaded method
first takes initial criteria and second
parameter is Collectors object.
And hence we can use any method which
returns collectors object as second
parameter.. So, we passed another
groupingBy() method to further classify
employees based on the role in each city.
EMP ID City Salary Role
1 MEL 250 Developer
3 MEL 150 Developer
2 SYD 230 Developer
6 BRS 400 Director
5 SYD 350 Developer
7 SYD 100 Manager
4 MEL 200 Manager
List<Employee>
BRS MEL
DeveloperDirector Manager
[Emp6] [emp1, emp3] [Emp4]
SYD
Developer Manager
[emp5, emp2] [Emp7]
.. Continued
Parallel stream.
Note, that parallelism is not automatically faster than performing operations serially, although it can be if you have
enough data and processor cores.
List<Long> melEmpIds = employeeList.parallelStream()
.filter(emp -> emp.getCity().equals("MEL")
&& emp.getSalary() < 250)
.map(emp -> emp.getEmployeeId())
.collect(toList());
Aggregate operations and parallel streams enable
you to implement parallelism with non-thread-safe
collections provided that you do not modify the
collection while you are operating on it.
Read Stream of Lines from a File
Stream<String> streamOfLines = Files.lines(Paths.get(”/tmp/transaction.csv”));
The above code reads the file from path specified and creates stream of
Line. Each line is represented in the String format.
Happy Learning!
1. http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html
2. http://www.oracle.com/technetwork/articles/java/architect-streams-pt2-2227132.html
3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html
5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
References

More Related Content

PPTX
Comparing 30 Elastic Search operations with Oracle SQL statements
PPTX
Designing REST API automation tests in Kotlin
PDF
Presentation of the new OpenERP API. Raphael Collet, OpenERP
KEY
Metaprogramming in Haskell
PPT
Plone For Developers - World Plone Day, 2009
PDF
Swift에서 꼬리재귀 사용기 (Tail Recursion)
PDF
Groovy's Builder
PPTX
ProgrammingwithGOLang
Comparing 30 Elastic Search operations with Oracle SQL statements
Designing REST API automation tests in Kotlin
Presentation of the new OpenERP API. Raphael Collet, OpenERP
Metaprogramming in Haskell
Plone For Developers - World Plone Day, 2009
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Groovy's Builder
ProgrammingwithGOLang

What's hot (20)

PDF
Ruby on Rails ステップアップ講座 - 大場寧子
PDF
Closure, Higher-order function in Swift
ODP
Grails: a quick tutorial (1)
PDF
Everything you always wanted to know about forms* *but were afraid to ask
PDF
Leveraging Symfony2 Forms
PDF
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
PDF
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
PDF
레진코믹스가 코틀린으로 간 까닭은?
PDF
Writing Your App Swiftly
PDF
Kotlin: Let's Make Android Great Again
PDF
Error Management: Future vs ZIO
PDF
Rust ⇋ JavaScript
PDF
Rails on Oracle 2011
PPTX
Ruby on rails tips
PDF
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
ODP
Learn JavaScript by modeling Rubik Cube
PDF
Emerging Languages: A Tour of the Horizon
PPTX
Apache spark
Ruby on Rails ステップアップ講座 - 大場寧子
Closure, Higher-order function in Swift
Grails: a quick tutorial (1)
Everything you always wanted to know about forms* *but were afraid to ask
Leveraging Symfony2 Forms
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
레진코믹스가 코틀린으로 간 까닭은?
Writing Your App Swiftly
Kotlin: Let's Make Android Great Again
Error Management: Future vs ZIO
Rust ⇋ JavaScript
Rails on Oracle 2011
Ruby on rails tips
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Learn JavaScript by modeling Rubik Cube
Emerging Languages: A Tour of the Horizon
Apache spark
Ad

Similar to Processing Collections with Java8 Stream APIs (20)

PPTX
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
PPTX
Java 8 streams
PDF
Concept of Stream API Java 1.8
PDF
Lambda.pdf
PPTX
Eclipse Day India 2015 - Java 8 Overview
PPTX
FUNctional Programming in Java 8
PDF
Harnessing the Power of Java 8 Streams
PDF
Fp java8
PPTX
ADT02 - Java 8 Lambdas and the Streaming API
PDF
Collectors in the Wild
PDF
The map interface (the java™ tutorials collections interfaces)
PPTX
Java 8 lambda
PDF
Java Lambda internals with invoke dynamic
PPTX
Functional programming in java
PPTX
Introduction to java 8 stream api
PPTX
Java 8 stream and c# 3.5
PDF
Java Streams Interview short reminder with examples
PDF
CBStreams - Java Streams for ColdFusion (CFML)
PDF
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
PDF
Java 8 - functional features
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 streams
Concept of Stream API Java 1.8
Lambda.pdf
Eclipse Day India 2015 - Java 8 Overview
FUNctional Programming in Java 8
Harnessing the Power of Java 8 Streams
Fp java8
ADT02 - Java 8 Lambdas and the Streaming API
Collectors in the Wild
The map interface (the java™ tutorials collections interfaces)
Java 8 lambda
Java Lambda internals with invoke dynamic
Functional programming in java
Introduction to java 8 stream api
Java 8 stream and c# 3.5
Java Streams Interview short reminder with examples
CBStreams - Java Streams for ColdFusion (CFML)
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
Java 8 - functional features
Ad

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Lesson notes of climatology university.
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Complications of Minimal Access Surgery at WLH
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Classroom Observation Tools for Teachers
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
GDM (1) (1).pptx small presentation for students
A systematic review of self-coping strategies used by university students to ...
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
102 student loan defaulters named and shamed – Is someone you know on the list?
Lesson notes of climatology university.
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Microbial diseases, their pathogenesis and prophylaxis
Final Presentation General Medicine 03-08-2024.pptx
Cell Types and Its function , kingdom of life
Supply Chain Operations Speaking Notes -ICLT Program
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Complications of Minimal Access Surgery at WLH
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Classroom Observation Tools for Teachers
Chinmaya Tiranga quiz Grand Finale.pdf
O7-L3 Supply Chain Operations - ICLT Program
Pharmacology of Heart Failure /Pharmacotherapy of CHF

Processing Collections with Java8 Stream APIs

  • 1. JAVA 8 STREAMS Zameer Ahmed Shaik. Senior Full Stack Java Engineer.
  • 2. • Introduction • Processing Collections - Java7 Vs Java8 • Introducing Java8 Stream APIs. • Basic operations using Streams • Advanced operations. • Parallel stream. • Read Stream of Lines from a File. In This Tutorial ..
  • 3. • Java Stream is an abstraction that lets you process data in a declarative way. • Perform SQL like operations on Collections. • process really large collections efficiently By leverage Multi core architectures. What is Stream ?
  • 4. Processing Collections - Java7 Vs Java8 • Find the list of employee ids sorted based on their Salary in a given city. List<Employee> employeeList = StreamDemoHelper.getEmployeeList(); EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 Each row in the above table represents Employee Object.
  • 5. List<Employee> employeeList = StreamDemoHelper.getEmployeeList( List<Employee> melboureEmployees = new ArrayList<>(); for(Employee emp : employeeList){ if(emp.getCity().equals("MEL")){ melboureEmployees.add(emp); } } Collections.sort(melboureEmployees, new Comparator<Employee>(){ @Override public int compare(Employee o1, Employee o2) { return o2.getSalary().compareTo(o1.getSalary()); } }); List<Long> melEmpIdList = new ArrayList<>(); for(Employee emp : melboureEmployees){ melEmpIdList.add(emp.getEmployeeId()); } Processing Collections - Java7 1. Iterate the list of Employees and check each employees city and add it to a separate list. 2. Sort the list of Employees in Melbourne based on salary. 3. Iterate Melbourne employees and then add it to separate list of ids. Output: [1, 4, 3]
  • 6. List<Long> empIds = employeeList.stream() .filter(emp -> emp.getCity().equals("MEL")) .sorted(comparing(Employee::getSalary) .reversed()) .map(emp -> emp.getEmployeeId()) .collect(toList()); Processing Collections – Java8 Only Declare what need to be performed using Steam APIs. This code will produce the same result as that of previous code. Don’t worry if you don’t understand, we will see all the Stream APIs in the next slides.
  • 7. stream() filter() sorted() collect() toList() toMap() toSet() sum() count() avaragingInt() map() averagingLong() averagingDouble() groupingBy() reduce() minBy() maxBy() limit() skip() allMatch() findAll() findAny() partitioningBy() flatMap() joining() mapping() collecting() Java8 Stream APIs
  • 8. 1. Filter Employees based on city. 2. Total number of people whose salary greater than $230 3. Find List of Employee ids whose salary is less than $250 of a given city. 4. Distinct Cities in which employees has salaries less than $250 5. Find total amount of money spent on Salaries Every Month. 6. Other operations.. Basic operations using Streams
  • 9. Filter Employees based on city. EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 EMP ID City Salary 1 MEL 250 3 MEL 150 4 MEL 200 List<Employee> melEmpList = employeeList.stream() .filter(emp -> emp.getCity().equals("MEL")) .collect(Collectors.toList()); filter() method takes lamda expression of Predicate type and filters the stream based on the condition defined. collect() method collects the filtered Steam objects and converts it to List of Employee objects using Collectors.toList() method defined inside it. Collectors class has toSet(), toMap(), toConcurrentMap(), toCollection() methods to convert the stream of objects to a particular type of collection.
  • 10. Total number of people whose salary greater than $230 EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 Long count = employeeList.stream() .filter(emp -> emp.getSalary() > 230) .count(); Filter employees whose salary is greater than $250 count() will return the total of the filtered items. count = 3
  • 11. Find List of Employee ids whose salary is less than $250 of a given city. List<Long> melEmpIds = employeeList.stream() .filter(emp -> emp.getCity().equals("MEL") && emp.getSalary() < 250) .map(emp -> emp.getEmployeeId()) .collect(toList()); filter method actually return stream of employee objects which is Stream<Employee>. map() functions comes to our rescue to create a stream of whatever we want based on the employee object. map() function returns stream of whatever that is returned in the lamda expression that is passed to it. In our case map() function returns Stream of employee ids. EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 EMP ID City Salary 1 MEL 250 3 MEL 150 4 MEL 200 [3, 4] filter() map()
  • 12. some more examples of map() function… List<Bonus> bonusList = employeeList.stream() .map(emp -> new Bonus(emp.getEmployeeId(), emp.getSalary() * 1.5)) .collect(toList()); The Lamda expression of map() function returns Bonus object based on Employee object and hence we get Stream of Bonus objects which is Stream<Bonus> whoAmI = employeeList.stream() .map(emp -> { Integer tax =calculateTaxes(emp); //Date date = get payroll date. return new Payroll(emp.getEmpId, emp.geSalary, date, tax); }) .collect(toList()); Guess what is the type of whoAmI ? It is List<Payroll>
  • 13. Find total amount of money spent on Salaries Every Month. EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 Long sumOfSalaries = employeeList.stream() .mapToLong(emp -> emp.getSalary()) .sum(); sum() will return the total of all the salaries. }Total = 1680 mapToLong() is similar to map() function except map() returns Stream<Object> whereas maptoLong returns LongStream object and helps us perform sum() of all the Longs. Similarly, we have mapToInt() & mapToDouble() to be used with Integer and Double.
  • 14. Distinct Cities in which employees has salaries less than $250 EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 List<String> distinctCities = employeeList.stream() .filter(emp -> emp.getSalary() < 250) .map(emp -> emp.getCity()) .distinct() .collect(toList()); First filtering employees whose salary is less than $300 distinct() method basically removes all the duplicates. MEL MEL SYD SYD filter() [MEL, SYD] distinct()
  • 15. Other Operations.. Check whether all the employees have salary greater than $75. In this case it will return true. Boolean allMatch = employeeList.stream() .allMatch(emp -> emp.getSalary() > 75); Double averageLong = employeeList.stream() .collect(averagingLong(Employee::getSalary)); Highest & Lowest salaried employees. Average salary in the company Optional<Employee> minSalariedEmployee = employeeList.stream() .collect(minBy(comparing(Employee::getSalary))); For maximum salaried employee use maxBy() function of Collectors class. Please check Collectors method for other functions like reducing(), joining(), mapping() etc.
  • 16. 1. Group employees based on whether salary greater than $250 2. Group employees based on City and order by Salary 3. Group employees based on city and then group each city by the role of the employee and order by salary. Advance operations using Streams
  • 17. 1. Group employees based on whether salary greater than $250 Map<Boolean , List<Employee> > partitionByMap = employeeList.stream() .collect(Collectors.partitioningBy(emp -> emp.getSalary() > 250)); partitioningBy() method groups the collection based on the codition passed to it. In this case employees are grouped based on whether their salary is greater than $250. EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 true [emp6, emp5] false [emp1, emp3, emp2, emp7, emp4] Map<Boolean, List<Employee>> List<Employee>
  • 18. Group employees based on City whose salary > 150 and order by Salary Map<String, List<Employee>> groupByCity = employeeList.stream() .filter(emp -> emp.getSalary() > 150) .sorted(comparing(Employee::getSalary).reversed()) .collect(Collectors.groupingBy(emp -> emp.getCity())); Collectors.groupingBy() is used to group the collection based on the return type of the lamda defined in it. In this case we are grouping based on the City. Just Note that in this case , grouping happens on the filtered and sorted collection which we passed to the collect method. EMP ID City Salary 1 MEL 250 3 MEL 150 2 SYD 230 6 BRS 400 5 SYD 350 7 SYD 100 4 MEL 200 BRS [emp6] MEL [emp1, emp4] SYD [emp5, emp2] Map<String, List<Employee>> List<Employee>
  • 19. Id=1 $250, MEL Id=3 $150,MEL Id=2 $230,SYD Id=6 $400,BRS Id=5 $350,SYD Id=7 $100,SYD Id=4 $200,MEL Id=1 $250, MEL Id=2 $230,SYD Id=6 $400,BRS Id=5 $350,SYD Id=4 $200,MEL Id=6 Id=2 $230, SYD Id=4 $200,MEL Java 8 Streams – Filter, Sort on Salary & Group by City .filter(e -> e.getsalary > 150) empList.stream() .sorted( comparing( e -> e.getPrice)) $400,BRS Id=5 $350,SYD Id=1 $250, MEL groupingBy( emp -> emp.getCity) Id=6 $400,BRS Id=5 $350,SYD Id=2 $230, SYD Id=1 $250, MEL Id=4 $200,MEL BRS SYD MEL ..continued
  • 20. Group employees based on city and then group each city by the role of the employee and order by salary. Map<String, Map<String, List<Employee>>> groupByCityAndRole = employeeList.stream() .sorted(comparing(Employee::getSalary).reversed()) .collect(groupingBy(emp -> emp.getCity(), groupingBy(emp -> emp.getRole()))); Collectors.groupingBy() overloaded method first takes initial criteria and second parameter is Collectors object. And hence we can use any method which returns collectors object as second parameter.. So, we passed another groupingBy() method to further classify employees based on the role in each city.
  • 21. EMP ID City Salary Role 1 MEL 250 Developer 3 MEL 150 Developer 2 SYD 230 Developer 6 BRS 400 Director 5 SYD 350 Developer 7 SYD 100 Manager 4 MEL 200 Manager List<Employee> BRS MEL DeveloperDirector Manager [Emp6] [emp1, emp3] [Emp4] SYD Developer Manager [emp5, emp2] [Emp7] .. Continued
  • 22. Parallel stream. Note, that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. List<Long> melEmpIds = employeeList.parallelStream() .filter(emp -> emp.getCity().equals("MEL") && emp.getSalary() < 250) .map(emp -> emp.getEmployeeId()) .collect(toList()); Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided that you do not modify the collection while you are operating on it.
  • 23. Read Stream of Lines from a File Stream<String> streamOfLines = Files.lines(Paths.get(”/tmp/transaction.csv”)); The above code reads the file from path specified and creates stream of Line. Each line is represented in the String format.
  • 24. Happy Learning! 1. http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html 2. http://www.oracle.com/technetwork/articles/java/architect-streams-pt2-2227132.html 3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html 4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html 5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html References