Stream, Filter and Collect List Items

Venkatesh Vinayakarao
Java Developers
Published in
3 min read1 day ago

Java: Simple and Short: A working example.

Let us learn Java Streams

Introduced in Java 8, Stream API is used to process collections of objects.

Here is a simple fully working code example which filters a list based on some condition using Stream.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TryStream {

public static void main(String[] args) {

tryStream();
}

private static void tryStream() {

//Create two laptop instances
Laptop laptop1 = new Laptop(LaptopType.WIN);
Laptop laptop2 = new Laptop(LaptopType.MAC);

//Put them in a list
List<Laptop> laptops = new ArrayList<>();
laptops.add(laptop1);
laptops.add(laptop2);

//Keep only Win type laptops in the list
laptops = laptops.stream()
.filter(laptop -> laptop.getType()
.equals(LaptopType.WIN))
.collect(Collectors.toUnmodifiableList());

//See that we have only "WIN" in the list.
for (Laptop laptop : laptops) {
System.out.println(laptop.getType());
}
}
}

enum LaptopType {

WIN,
MAC;
}

class Laptop {

private LaptopType type;

public Laptop(LaptopType type) {

this.type = type;
}

public LaptopType getType() {

return type;
}
}

We create two laptop instances. One of them is of type Windows and the other is a Mac. We put them in a list. We filter the list to have only the Windows laptop. Finally, we print the contents of the list to ensure that it has only the Windows laptop.

For this story, let us focus on the following part of the code.

laptops = laptops.stream()
.filter(laptop -> laptop.getType()
.equals(LaptopType.WIN))
.collect(Collectors.toUnmodifiableList());

A less sophisticated programmer would have used a loop to iterate over the contents if laptops list to removed the Mac.

As you see, we do three things:

  1. Stream the contents of the list
  2. Filter based on some condition
  3. Collect the results

There is quite a lot to learn in each of them. By following this approach, we avoided looping. Not just that. We use chaining of three functions. This design allows us to follow a declarative approach by actually doing anything only in the final step, i.e., collect. This is called lazy evaluation.

Stream the contents

There are multiple ways to create an instance of Stream.

  • From an array: Use Arrays.stream(array) to create a stream from an array.
  • From a set of values: Use Stream.of(value1, value2, ...) to create a stream from a fixed set of values.
  • Using a Stream.Builder: Use Stream.builder() to create a stream by adding elements one by one.

Filter the contents

Filter method includes an element if the defined predicate is true. In our case, we coded the predicate as

laptop -> laptop.getType().equals(LaptopType.WIN)

This is a lambda expression with a single parameter. If you are new to lambda expressions, I recommend the following short video to you.

Collect the results

While executing this line is when the JVM actually does all the streaming, filtering and collecting. Hence, this is called a terminal operation. To cut the long story short, Java has a Collectorinterface. There are many implementations of the Collector.collect() method. For example, we can collect lists, sets, etc. Keep in mind that the default implementation in Java is highly parallelized, thanks to the stateless nature of these operations. In simple words, it means that if we have multiple cores, we can create parallel streams and do the filter operation in each of them in parallel. Collector knows how to put them together to get the final result.

Note that Intellij will suggest an improvement. Instead of .collect(Collectors.toUnmodifiableList()) you could just use toList().

laptops = laptops.stream()
.filter(laptop -> laptop.getType()
.equals(LaptopType.WIN))
.toList();

The purpose of these “Simple and Short” stories is to pick one small feature of Java, highlight it with a fully working code, and discuss the fundamentals. Hope you learned something today.

--

--

Venkatesh Vinayakarao
Java Developers

Principal Engineer (with a leading map making company) | PhD in Computer Science | Interested in Computer Science, Information Retrieval, Chess and Finance.