{{announcement.body}}
{{announcement.title}}

Java Streams: An Implementation Approach

DZone 's Guide to

Java Streams: An Implementation Approach

In this tutorial, we will learn what Streams are in Java by comparing the Stream API to SQL statements as an implementation approach.

· Java Zone ·
Free Resource

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


2. long count();

Query: find the total number of students in the Student table

Stream Code:

Java


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

Stream Code:

Java


3. Stream<T> limit(long maxSize);

Query: find the first 10 students from the Student table whose name starts with 'A'.

Stream Code: 

Java


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


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


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


7.Optional<T> findFirst();

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

Stream Code:

Java


Please find below the full code for the above mention Stream API methods:

Java


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

Topics:
java 1.8, java 8, streams, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}