Tag Archives: clean code

Java

Java 8 – Streams API instead of FluentIterable

In one of my recent posts I was comparing FluentIterable with Java 8 Lambdas (here). Now let’s take a look at how Streams API introduced in Java 8 changed way we write code.

What is Streams API?

Streams are not Collections. Streams are lazy data structures that compute values on demand. It is important to know that Streams have two types of operations:

  • intermediate – those operations return stream and can be combined into pipeline. For example filter, map, etc
  • terminal – those operations returns final result. For example sum, count, etc.

So lets start usage of Streams API with some POJO class.

Now imagine case where we want to calculate count of items which name ends with “C”.

As you can see in this example code written with Streams API is very readable. I added comments, but basically you can read code as normal sentences. Moreover it has big advantage over Guava implementation because you don’t have to create inner class implementing Predicate and Function interfaces.

Also it is easier to create new collection based on results of pipeline processing by using Collectors.

As you can see from this two examples Streams API is very easy to use and makes code really clean. It changes way of writing code from imperative to declarative.

More to read