Skip to main content

Command Palette

Search for a command to run...

Learn Java 8 Streams API[Practically]

Using Java 8 streams; Java 8 streams learning resources

Updated
5 min read
Learn Java 8 Streams API[Practically]
D

Divine is a software developer who is interested in product management and writing(Non-Fiction, Technical Articles)

Table of contents

What is the streams API all about?

Streams bring functional programming to Java. The heavy use of lambda expressions gives it a JavaScript-like feeling.

IntStream
        .range(1, 10)
        .skip(5)
        .forEach(x -> System.out.println(x));/* Use of lambda expressions */

A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce. - Oracle Docs

 

Stream operations are eitherintermediate or terminal.

Intermediate operations

Screenshot from 2021-02-28 16-22-55.png

Intermediate stream operations receive a Stream Input and returns Stream Output, so we can chain multiple intermediate operations.

The piece of code 👇🏾 returns a stream that can be passed to another intermediate or terminal operation

Stream.of(2, 1, 3)// Stream
      .sorted();// Intermediate operation

Terminal operations

Screenshot from 2021-02-28 16-28-16.png

Terminal stream operations receive a Stream Input and returns Non-stream Output or Void.

The piece of code 👇🏾 performs a terminal operation forEach() to print the stream values sorted by the intermediate operation sorted().

Stream.of(2, 1, 3)//Stream
      .sorted()//Intermediate operation
      .forEach(System.out::println);//Terminal operation

For more examples of using Java Streams, checkout JavaTpoint and this GitHub repo.

Advantages

  • Simpler and cleaner code.
  • Using Streams will make you a more efficient Java programmer
  • Streams encourage looser coupling. Your stream-handling code doesn't need to know the source of the stream, or its eventual terminating method - Source

When should it be used?

Well, every time 😁... every time possible. Reading about streams, and its advantages you would want it throughout your code.

Now to what you've been waiting for; Practical scenarios.

Using Java 8 streams practically

Task 1

Checks from a list of airplanes if they all meet the criteria of a cargo plane

Using Streams

Below are chained stream operations

boolean areCargoPlanes = airplanes
        .stream()
        .filter(airplane -> airplane.getLoadCapacity() > 705)/*Hypothetical load of small planes */
        .filter(airplane -> airplane.getNumberOfSeats() < 5)
        .allMatch(airplane -> airplane.isCargo());

Without Streams

The code below is not an exact match of what the code with the Stream API does.

boolean areCargoPlanes = false;

for (String airplaneStr: airplanes) {
    if (airplane.getLoadCapacity() > 705) { //Hypothetical load of small planes
        if (airplane.getNumberOfSeats() < 5) {
            if (airplane.isCargo()) {
                areCargoPlanes = true;  
            }else {
                break;
            }
        }
    }
}

Task 2

From a list of guests in a hotel, print guests first and last name in alphabetical order.

Using Streams

List<RoomGuest> hotelGuests = new ArrayList<>();

hotelGuests.stream().sorted((o1, o2) -> {
    if (o1.getLastName().equals(o2.getLastName())) {
        return o1.getFirstName().compareToIgnoreCase(o2.getFirstName());
    }
    return o1.getLastName().compareTo(o2.getLastName());
}).forEach(System.out::println);

Without Streams

Just imagine the amount of code.

Resources

The best resource is Oracle's documentation on Java Stream API.

  1. Java 8 STREAMS Tutorial on Youtube
  2. The Java 8 Stream API Tutorial by Baeldung blog.
  3. An In-Depth guide to Java 8 Stream API by Java2Blog
  4. A Guide to Java Streams in Java 8: In-Depth Tutorial With Examples by Stackify blog.

Summary

In this post, we've learnt about Java 8 Streams and seen its benefits.

Knowledge of Java 8 streams is very essential and will come in handy as a beginner developer meeting a new codebase.

Thank you for reading. I mostly write tutorials on the problems I have faced and whatever new tech I explore, so stay tuned for the next article(I will be writing about files conversion).

If you found this article helpful, react and share. Cheers.

And you can follow me on Twitter.

S

Great description of Java streams API - thank you for this. I've outlined some cool ones for myself to have a look at (Baedlung rocks at the moment among other sources). Also, you may find helpful the article on the same topic on Codegym .

1
D

Thank you Stella Aldridge. Definitely checking out the article now. I am glad you liked the article.

More from this blog

ProductDev

13 posts

I mostly write tutorials on the problems I have faced and whatever new tech I explore.