Java Streams: An Implementation Approach
Join the DZone community and get the full member experience.
Join For FreeIn this tutorial, we will learn what Streams are in Java and how we can develop an implementation approach. We will compare the Stream API to SQL statements as an implementation approach.
Audience
All Java Developers who want to learn the new feature of Java 8 i.e. Streams API.
Recommended
We strongly recommend checking the source code of the Stream Interface to better understand some of its inner-workings.
Introduction to Streams API
A Stream represents a sequence of objects from a source, which supports aggregate operations. A Stream is used to perform complex data processing operations, like filter, matching, mapping etc.
We can visualize a Stream as an approach to process data in a declarative way similar to a SQL statement.
Let's assume we have a Student table with the following data:
Student_id |
First_name |
Last_name |
Roll_no |
Grade |
Total_marks |
1 |
Akshay |
Singh |
1 |
V |
900 |
2 |
Aman |
Pal |
2 |
V |
700 |
3 |
Bharat |
P |
3 |
V |
750 |
4 |
Piyush |
Chandra |
4 |
V |
990 |
5 |
Atul |
Kumar |
5 |
V |
1000 |
The corresponding Class for the Student table is:
Now, we will use the Stream API to visualize it as SQL statement.
1. Stream<T> filter(Predicate<? super T> predicate);
Query: find all students from the Student table whose first name starts with 'A'.
Stream Code:
xxxxxxxxxx
List<Student> filteredList = studentList.stream().filter((Student s)-> s.firstName.startsWith("A")).collect(Collectors.toList());
2. long count();
Query: find the total number of students in the Student table
Stream Code:
xxxxxxxxxx
long totalstudent= studentList.stream().count();
Query: find total number of students in the Student table whose name starts with 'A'.
Stream Code:
xxxxxxxxxx
long totalStudent= studentList.stream().filter((Student s)-> s.firstName.startsWith("A")).count();
3. Stream<T> limit(long maxSize);
Query: find the first 10 students from the Student table whose name starts with 'A'.
Stream Code:
xxxxxxxxxx
List<Student> limitList= studentList.stream().filter((Student s)-> s.firstName.startsWith("A")).limit(10).collect(Collectors.toList());
4. Optional<T> min(Comparator<? super T> comparator);
Query: find a student from Student table who is has a minimum total marks of all the students.
Stream Code:
xxxxxxxxxx
Comparator<Student> mincomparator = Comparator.comparing( Student::getTotalmarks);
Student minMarks = studentList.stream().min(mincomparator).get();
5. Optional<T> max(Comparator<? super T> comparator);
Query: find a student from the Student table who has the maximum total marks of all the students.
Stream Code:
xxxxxxxxxx
Comparator<Student> maxcomparator = Comparator.comparing( Student::getTotalmarks);
Student maxMarks = studentList.stream().max(maxcomparator).get();
6.Stream<T> sorted(Comparator<? super T> comparator);
Query: find all students from the Student table in descending order of their total marks.
Stream Code:
xxxxxxxxxx
List<Student> sortedList = studentList.stream().sorted(Comparator.comparingInt(Student::getTotalmarks).reversed()).
collect(Collectors.toList());
7.Optional<T> findFirst();
Query: find the first student whose name starts with 'A'.
Stream Code:
xxxxxxxxxx
Optional<Student> firstStudent=studentList.stream().filter((Student s)-> s.firstName.startsWith("A")).findFirst();
Please find below the full code for the above mention Stream API methods:
xxxxxxxxxx
public class Student {
private int studentId;
private String firstName;
private String lastName;
private int rollNo;
private String grade;
private int totalmarks;
public Student(int studentId,String firstName,String lastName,int rollNo,String grade,int totalmarks) {
this.studentId=studentId;
this.firstName=firstName;
this.lastName=lastName;
this.rollNo=rollNo;
this.grade=grade;
this.totalmarks=totalmarks;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int getTotalmarks() {
return totalmarks;
}
public void setTotalmarks(int totalmarks) {
this.totalmarks = totalmarks;
}
public static void main(String[] args) {
List<Student> studentList=Arrays.asList(
new Student(1, "Akshay", "Singh", 1, "V",900),
new Student(2, "Aman", "Pal", 2, "V",700),
new Student(3, "Bharat", "P", 3, "V",750),
new Student(4, "Piyush", "Chandra", 4, "V",990),
new Student(5, "Atul", "Kumar", 5, "V",1000));
//find all student from Student table whose first name start with 'A'
List<Student> filteredList= studentList.stream().filter((Student s)->
s.firstName.startsWith("A")).collect(Collectors.toList());
//find total number of students in a Student table
long totalstudent= studentList.stream().count();
//find total number of students whose name start from 'A'
long totalStudent= studentList.stream().filter((Student s)->
s.firstName.startsWith("A")).count();
//find top 10 students from Student table whose name start from 'A'
List<Student> limitList= studentList.stream().filter((Student s)->
s.firstName.startsWith("A")).limit(10).collect(
Collectors.toList());
//find a student from Student table who is having minimum total marks
//of all the students.
Comparator<Student> mincomparator = Comparator.comparing(
Student::getTotalmarks );
Student minMarks = studentList.stream().min(mincomparator).get();
//find a student from Student table who is having maximum total marks
//of all the students.
Comparator<Student> maxcomparator = Comparator.comparing(
Student::getTotalmarks);
Student maxMarks = studentList.stream().max(maxcomparator).get();
//find all student from Student table in descending order of their
//total marks.
List<Student> sortedList = studentList.stream().sorted(
Comparator.comparingInt(Student::getTotalmarks)
.reversed()).collect(Collectors.toList());
//find the first student whose name start from 'A'
Optional<Student> firstStudent=studentList.stream().filter(
(Student s)-> s.firstName.startsWith("A")).findFirst();
}
}
In the next tutorial, we will deep dive some more Stream API methods with increased complexity.
Opinions expressed by DZone contributors are their own.
Comments