Enable Javascript

Please enable Javascript to view website properly

Toll Free 1800 889 7020

Looking for an Expert Development Team? Take 2 weeks Free Trial! Try Now

What is Stream API in JDK 1.8?

Introduction

Stream API in JDK

Stream API was introduced in the JDK 1.8 release for the sole purpose to ease the way to deal with collections of objects, or we can say that stream of objects/elements stored in a Collection API implementation classes (LIST, MAP, etc.).

In this blog, Outsource java development team discuss the intermediate operations/methods present in the Stream API its popular functions and operations.

Stream API intermediate methods

This method is called the intermediate method because the result or return type of this method is a Stream itself.

List of intermediate methods are:

  • 1. filter()
  • 2. map()
  • 3. flatMap()
  • 4. distinct()
  • 5. sorted()
  • 6. peek()
  • 7. limit()
  • 8. skip().

Terminal operations/methods of Stream API

This method is called the terminal method because the return type of this method will be a non-stream element, such as primitive value, a collection, or no value at all.

One thing to note this method should be or can be called only after intermediate methods in precedence.

List of Terminal methods are:

  • 1. toArray()
  • 2. collect()
  • 3. count()
  • 4. reduce()
  • 5. forEach()
  • 6. min()
  • 7. max()
  • 8. anyMatch()
  • 9. forEachOrdered()
  • 10. allMatch()
  • 11. noneMatch()
  • 12. findAny()
  • 13. findFirst()

Let’s understand each intermediate and terminal method in detail.

filter():

As the name suggests, this intermediate method will filter the Stream elements based on the predicate passed. For example, you want to get only even numbers from the list of numbers, you can easily do it using filter () and passing a predicate argument for the filter.

Predicate: It takes predicate reference as an argument. A predicate is a functional interface, so we can also pass lambda expression here.

Code Examples:

1. Simple filter () method example and we have used forEach() end operations here.

Stream API in JDK

So in the image

In line 11, you will see I am creating a List of Indian city names.

At line 13, I have called the stream () method on the names list reference variable, stream () will convert the names list to stream, after stream () if called filter () method and inside the filter method I have passed a predicate name with lambda operator and after that trying to compare the values of predicate reference i.e. name with one of the List value.

I am trying to print all the city names which are not equal to Mumbai and present in the list.

End operation I am doing with the help of forEach() loop, which is again accepting a predicate as an argument with Lambda operator.

And then, trying to print the namely predicate, which will hold all the city names which are not equal to Mumbai.

2. Filter() method example with findAny() and orElse() termination operations/methods.

Stream API in JDK

In the above image, again, I have created a vehicleList.

Again here I am converting vehicleList to stream and then calling filter() method in which trying to compare whether a value in the predicate x is equal to Honda or not.

In Line 17 if “Honda”.equals(x.getName()) returns true then findAny() termination method will be triggered and hence in Line 18 Honda will get printed in the console.

In Line 19 I am checking If “Yamaha”.equals(x.getName()) which returns false, hence orElse() method is triggered and thus null is printed in the console.

findAny() and orElse() method both work like if and else loop.

3. filter() method with map() method code example

Stream API in JDK
Stream API in JDK

So here in the above images, what I have done here is created an ExampleVehiclePojo with variables as name, engineCC, and manufacturer with setter and getter.

After that, in FilterMethodWithMapExample class, I have created a list vehicleList of ExampleVehiclePojo type and stored three ExampleVehiclePojo objects with different values.

At line number 16 in the above image, I am converting the vehicleList to stream and then calling filter () method on the stream. In filter method, I am checking whether the “Honda”.equals(x.getName()) and “1000”.equals(x.getEngineCC()) if both matches with the predicate i.e. x values coming from the stream then I am calling map() method, in map() method I am calling ExampleVehiclePojo :: getName which will get the Name from the ExampleVehiclePojo only if “Honda”.equals(x.getName()) and “1000”.equals(x.getEngineCC()) returns true and findAny() method is triggered, otherwise orElse() method will be triggered and which will print null.

Couple of things to note here

  • i) map() method is a functional programming concept introduced in java 1.8. It transforms one object into another by applying a function the map() method of Stream() API takes a function as an argument.
  • ii) (double colon) operator is also introduced in java 1.8, and it is used to refer to the methods of the existing class, whether it will be static or non-static methods.

4. FlatMap() method example

flatMap() method is used or we can say the sole purpose of flatMap() is to convert stream can hold different data types such as stream<String[]> stream<Set<String>> stream<List<String>>

But the stream operations like filter, sum, distinct, etc. and collectors do not support it,

So for that purpose we need flatMap() flatMap() will do the following conversion stream<String[]> to stream<String> stream<Set<String>> to stream<String> Below is code sample example
Stream API in JDK
Stream API in JDK

Here we are converting int[][] to IntStream using flatMap()

And also Set to Stream using flatMap()

Sorted() method code

Stream API in JDK

Here we are creating a gameList and then calling the sorted () function on the gameList stream, and finally, we are collecting the result using collect (Collectors.toList()).

The output will be list is sorted in lexicographic order

Stream API in JDK

peek() method example

Stream API in JDK

Here we are trying to find out the number is prime or not. And in the parallel stream that we have created by calling the parallel () method, we try to peek () and see the result and format it. And then count() it.

limit() method example

The limit() method allows the developer to limit the number of elements to be extracted from a stream.

It is useful in that application where the user wishes to process only the initial elements that occur in the stream.

Stream API in JDK

Conclusion

Here we have seen that we can use stream API operations on a collection of elements or Arrays.

And we can get our desired result as we want.

Specific points to note

  • Stream API is a look-alike of SQL query, here, in the stream API, we are pipelining all the intermediate operations and terminal operations. And finally, we will get the desired result in the form of collection or primitive data types or String types.
  • stream API is very useful when we deal with a collection of objects.
  • By using stream API, we can eliminate many boilerplate codes and unusual loops.
  • By using stream API, we can easily sort or limit the collection of objects and get our desired result.

So finally, stream API is the API that is introduced in java 1.8 to ease the outsourcing java development effort and get the desired result while dealing with a collection of elements, and get the desired result with less effort and time.

Software Development Team
Need Software Development Team?
captcha
🙌

Thank you!
We will contact soon.

Oops! Something went wrong.

Recent Blogs

Categories

NSS Note
Trusted by Global Clients