7 Useful Examples of the Java 8 Stream API

7 Useful Examples Java 8 Stream API

You probably already heard about the Java 8 Stream API (If not, you can find more information about it here). It’s basically an abstraction that allows us to process data in a simple and declarative way. Besides that, streams can leverage multi-core architectures without you having to write a single line of multi-thread code.

In this article we won’t describe each of the available methods on the Java 8 Stream API. Instead, we will focus on practical examples of how to consume this new API.

First of all, let’s present our Athlete model class:

Now, let’s initialize a List of Athletes with 6 objects…

Based on the previously presented List of Athletes, let’s now see how to easily manipulate this data and extract the information we want.

1. Getting the quantity of female athletes (filter + count)

2. Retrieving the list of American athlete names (filter + map + collect)

3. Checking whether all athletes were born in September or not (allMatch)

4. Mapping all athletes by country (collect)

5. Getting the Athletes’ average age (mapToInt + average + getAsDouble)

6. Returning the tallest Athlete (max + get)

7. Summing all Athletes’ height (mapToInt + sum)