Java 8 Stream filter example

In this tutorial we will provide examples of how to use the Java 8 Stream filter method. The filter method is self explanatory, it will filter any elements in a collection which does not satisfy the filter condition.

Simple Java 8 Stream filter example:

The example below shows how to filter a list of numbers greater then 2. Once we have filtered the elements, we can then chain it with a forEach i.e. execute some logic on the remaining elements that satisfied the filter condition.

Running the above code produces the following output

Another Java 8 Stream filter example:

The following example is filtering a list of objects based on the customers TvPackage.

As you can see from the example above you can provide any boolean condition to apply filtering on your collection. In the above example we used collect() to create a new list of GoldCustomers which we can apply some business logic too.

In conclusion I hope you found this post useful and he helped you understand the filter method in a little more detail.

Similar posts:

  1. Java 8 Streams map example
  2. Java 8 forEach examples
  3. Java 8 Comparator / sorting examples


  1. Java 8 Streams API Documentation




Leave a Reply