DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Bridge the Gap of Zip Operation
  • Multi-Threaded Geo Web Crawler In Java
  • Stretching Async/Await With Lambdas
  • Yet 4 More Techniques for Writing Better Java

Trending

  • Caching 101: Theory, Algorithms, Tools, and Best Practices
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Introduction to Retrieval Augmented Generation (RAG)
  1. DZone
  2. Data Engineering
  3. Databases
  4. Java Streams: An Implementation Approach

Java Streams: An Implementation Approach

By 
Kuldeep Pandey user avatar
Kuldeep Pandey
·
Aug. 11, 20 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
10.8K Views

Join the DZone community and get the full member experience.

Join For Free

In 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:

Example Student class

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: 

Java
xxxxxxxxxx
1
 
1
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:

Java
xxxxxxxxxx
1
 
1
long totalstudent= studentList.stream().count();


Query: find total number of students in the Student table whose name starts with 'A'.

Stream Code:

Java
xxxxxxxxxx
1
 
1
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: 

Java
xxxxxxxxxx
1
 
1
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:

Java
xxxxxxxxxx
1
 
1
Comparator<Student> mincomparator = Comparator.comparing( Student::getTotalmarks);
2

          
3
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:

Java
xxxxxxxxxx
1
 
1
Comparator<Student> maxcomparator = Comparator.comparing( Student::getTotalmarks);
2

          
3
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:

Java
xxxxxxxxxx
1
 
1
List<Student> sortedList = studentList.stream().sorted(Comparator.comparingInt(Student::getTotalmarks).reversed()).
2

          
3
collect(Collectors.toList());


7.Optional<T> findFirst();

Query: find the first student whose name starts with 'A'.

Stream Code:

Java
xxxxxxxxxx
1
 
1
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:

Java
xxxxxxxxxx
1
119
 
1
public class Student {
2

          
3
    private int studentId;
4
    private String firstName;
5
    private String lastName;
6
    private int rollNo;
7
    private String grade;
8
    private int totalmarks;
9

          
10
    public Student(int studentId,String firstName,String lastName,int rollNo,String grade,int totalmarks) {
11
        this.studentId=studentId;
12
        this.firstName=firstName;
13
        this.lastName=lastName;
14
        this.rollNo=rollNo;
15
        this.grade=grade;
16
        this.totalmarks=totalmarks;
17
}
18

          
19
    public int getStudentId() {
20
        return studentId;
21
    }
22

          
23
    public void setStudentId(int studentId) {
24
        this.studentId = studentId;
25
    }
26

          
27
    public String getFirstName() {
28
        return firstName;
29
    }
30

          
31
    public void setFirstName(String firstName) {
32
        this.firstName = firstName;
33
    }
34

          
35
    public String getLastName() {
36
        return lastName;
37
    }
38

          
39
    public void setLastName(String lastName) {
40
        this.lastName = lastName;
41
    }
42

          
43
    public int getRollNo() {
44
        return rollNo;
45
    }
46

          
47
    public void setRollNo(int rollNo) {
48
        this.rollNo = rollNo;
49
    }
50

          
51
    public String getGrade() {
52
        return grade;
53
    }
54

          
55
    public void setGrade(String grade) {
56
        this.grade = grade;
57
    }
58

          
59
    public int getTotalmarks() {
60
        return totalmarks;
61
    }
62

          
63
    public void setTotalmarks(int totalmarks) {
64
        this.totalmarks = totalmarks;
65
    }
66

          
67

          
68
    public static void main(String[] args) {
69
        List<Student> studentList=Arrays.asList(
70
                new Student(1, "Akshay", "Singh", 1, "V",900),
71
                new Student(2, "Aman", "Pal", 2, "V",700),
72
                new Student(3, "Bharat", "P", 3, "V",750),
73
                new Student(4, "Piyush", "Chandra", 4, "V",990),
74
                new Student(5, "Atul", "Kumar", 5, "V",1000));
75

          
76
        //find all student from Student table whose first name start with 'A'
77
        List<Student> filteredList= studentList.stream().filter((Student s)->
78
            s.firstName.startsWith("A")).collect(Collectors.toList());
79

          
80
        //find total number of students in a Student table
81
        long totalstudent= studentList.stream().count();
82

          
83
        //find total number of students whose name start from 'A' 
84
        long totalStudent= studentList.stream().filter((Student s)->
85
            s.firstName.startsWith("A")).count();
86

          
87
        
88

          
89
        //find top 10 students from Student table whose name start from 'A'
90
        List<Student> limitList= studentList.stream().filter((Student s)->  
91
            s.firstName.startsWith("A")).limit(10).collect(
92
            Collectors.toList());
93

          
94
        //find a student from Student table who is having minimum total marks
95
        //of all  the students.
96
        Comparator<Student> mincomparator = Comparator.comparing(
97
            Student::getTotalmarks );
98

          
99
        Student minMarks = studentList.stream().min(mincomparator).get();
100

          
101
        //find a student from Student table who is having maximum total marks
102
        //of all  the students.
103
        Comparator<Student> maxcomparator = Comparator.comparing(
104
            Student::getTotalmarks);
105

          
106
        Student maxMarks = studentList.stream().max(maxcomparator).get();
107

          
108
        //find all student from Student table in descending order of their
109
        //total marks.
110
        List<Student> sortedList = studentList.stream().sorted(
111
            Comparator.comparingInt(Student::getTotalmarks)
112
            .reversed()).collect(Collectors.toList());
113
      
114
       //find the first student whose name start from 'A'
115
        Optional<Student> firstStudent=studentList.stream().filter(
116
          (Student s)-> s.firstName.startsWith("A")).findFirst();
117

          
118
    }
119

          
120
}


In the next tutorial, we will deep dive some more Stream API methods with increased complexity.

Stream (computing) Java (programming language) Database Implementation

Opinions expressed by DZone contributors are their own.

Related

  • Bridge the Gap of Zip Operation
  • Multi-Threaded Geo Web Crawler In Java
  • Stretching Async/Await With Lambdas
  • Yet 4 More Techniques for Writing Better Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: