Sitemap

Java Stream API

5 min readJun 25, 2022

--

Intro

https://farticulate.files.wordpress.com/2010/12/grahd40446_5_m.jpg

Up on world of programming, there are two types of programming paradigms. Declarative programming and in contrast Imperative programming paradigms.

Declarative = WHAT , Imperative= HOW

The declarative paradigm is just specifying WHAT program needs to be done. And Control of flow is described implicitly. But the Imperative paradigm is just describing HOW needs to do a program by explicitly describing the Control of the Flow.

Let’s say we have the following list of elements. How to Print out elements using Declarative way and Imperative way.

List <String> listStr=new ArrayList<>();
listStr.add("Praneeth");
listStr.add("Anajalee");
listStr.add("Oshan");
listStr.add("Anoma");
listStr.add("Jayarathna");

Declarative way

for(String vals:listStr){
System.out.println(vals);
}

In Declarative programming one of the requirement is to describe every step of the program. It is the strength of describing the complex application in a more abstract way gradually. Hence it is easy to maintain the flow of the program.

Imperative way (Java Stream API)

listStr.stream().forEach(System.out::println);

Probably you may notice only one line of code is convenient rather than three lines of code. But sometimes this may lead to hard to understand for external people.

Nowadays we are using a mix of these two paradigms in most of the programs. And declarative programing language is being boosted with the Imperative paradigm.

Java, We have now these two types of paradigms. But before Java 8 only exists Imperative paradigm.

Basic Concepts of Java Stream API

Press enter or click to view image in full size

Intermediate and Terminal Operations are the main two type of the Operation consist in Stream function.

Intermediate operation, this operation is returning the Stream itself. It will make the chain of operations.

Terminal Operations , That’s mean when you use terminal operation you cannot do a operation after that.

How stream operations works

Press enter or click to view image in full size

Calling the Stream API

Let’s say we have class Student. Name, Age and List of marks are the feature of each of the student.

String name;
String age;
List marks;

Now we have a List of students details as below,

List<Student> studentList = new ArrayList<>();studentList.add(new Student("Praneeth","12", Arrays.asList("80","90","40")));

To call to the Stream API we can proceed two way.

First way is using Stream interface

Stream.of(studentList);

Or changing Our Collection into stream

studentList.stream()

Both two ways, it is getting the same result as Stream Object.

Printing All elements using For Each

terminal operation

studentList.stream().forEach(student-> System.out.println(student));

Here studentList is converting into Stream , using forEach loop

Or We can just calling the println without create a lambda function

studentList.stream().forEach(System.out::println);

Filter

Filter is an intermediate operation.

Get Praneeth PJ’s stories in your inbox

Join Medium for free to get updates from this writer.

Now we need the Filtering the values from the List.

studentList.stream()
.filter(student -> student.getAge()>10).forEach(result->System.out.println(result));

Filter operation is taking predicate and it is based on true or false values. This will be filtered students aged greater than 10.

Then the result is displaying using foreach operation.

Find First

Lets say we want to get the first item of the Filtered List.

To do that we can use FindFirst(). The FindFirst return the Optional object. That mean it optionally return the value. It might have the Student or might not. That mean if the value does exists that Ok. But when value does not exist, we need to do some other else operation. Like throw an exception, return a dummy value or pass null value.

Another point is that FindFirst is a terminal operation. Hence it is returning the Object. In our case, it is returning the Student Object.

Student studentResult= studentList.stream()
.filter(student -> student.getAge()>10).findFirst().orElse(null);
System.out.println(studentResult);

Map

Map operation also an intermediate operation.

Map uses to mapping sequence of elements and reform that into a another stream.

Previously we filtered list the list of student’s age more than 10. Let’s say we need to modify that list based on the filter operation. Adding a label in front of the name as Group A.

studentList.stream()
.filter(student -> student.getAge()>10)
.map(student -> new Student("Group A : "+student.getName(),student.getAge(),student.getMarks()))
.forEach(System.out::println);

After the filter operation the matched result is passing into the map operation. in map operation, we are passing the values for modification and values of the current list. Then it returns a modified List.

Flat Map

Flatmap is a another intermediate operation.

Flat map allow accessing the List of streams. That means here we have a List of List as Students Mark. Mark is another list relying on the Student List.

Our applicability is getting the mark of all students whose ages are greater than 10.

studentList.stream()
.filter(student -> student.getAge()>10)
.map(student -> student.getMarks())
.flatMap(studentMarks ->studentMarks.stream())
.forEach(System.out::println);

First filter the students and using map create stream List of Marks. Because we are map over the student object to the List of marks. Flat map operation is converting the previous List of marks into studentMarks of Stream. It is really converting to the List into the Object type.

Sorting

studentList.stream()
.sorted((n1,n2)->n1.getName().compareToIgnoreCase(n2.getName()))
.forEach(System.out::println);

Sort is taking comparator. A comparator object is capable of comparing two objects. Here the result is Ascending order.

But if you wish to have a descending order just change the place of comparator variable.

studentList.stream()
.sorted((n2,n1)->n1.getName().compareToIgnoreCase(n2.getName()))
.forEach(System.out::println);

Short circuit operations

Short circuit operations are using to limit the result of data.

studentList.stream()
.skip(1)
.limit(2)
.forEach(System.out::println);

This will be skipped the first record and showed Only 2 records.

Min and Max

Lets see if we want to get the Min and Max age from the List.

Object studentResult= studentList
.stream()
.max(Comparator.comparing(Student::getAge)).get();
System.out.println(studentResult);

Comparator is an interface and after passing the Age it will return Sorted values.

You may try min as same way as changing the Max function

Object studentResult= studentList
.stream()
.min(Comparator.comparing(Student::getAge)).get();
System.out.println(studentResult);

Reduce

Reduce uses to accumulate the data. For example lets say we want to get average, total like operation of the List.

Integer studentResult=studentList.stream()
.map(student -> student.getAge())
.reduce(0, (subtotal, element) -> subtotal + element);

System.out.println(studentResult);

First it is creating age values age stream of values. In reduce function first argument contains the initial value and the default value if stream is empty. Next argument is accumulator. It is a function that takes two parameters. A partial result of the reduction operation and the next element of stream.

Finaly this is getting the sum of the age.

Parallel Stream

So far we discussed the Sequence stream. But in parallel stream utilized the multiple cores of the processor. That mean we can divide the code into multiple streams that are executed in parallel on separate cores. Final result is the combination of the individual outcomes.

I hope to cover this in a upcoming article

--

--