In the last couple of Java 8 tutorials, you have learned how to use map(), flatMap(), and other stream examples to get an understanding of how Java 8 makes it easy to perform the bulk data operation on Collection classes. In this example, I am going to share how to use the filter() method in Java 8, another key method of Stream class. The filter() method as it name suggests is used to perform filtering e.g. if you have a stream of numbers you can create another stream of even numbers by using the filter() method. Though, filter() method is little bit of counter intuitive i.e. in order to create a stream of even number you call filter( i -> i%2 == 0) which means you do filter(isEven()) but, you are actually filtering odd numbers to create a new stream of even numbers, but that's how it works. The key benefit of using filter() method is lazy evaluation i.e. no data comparison is performed unless you call a terminal operation on stream e.g. findFirst() or forEach(). The filter() method just set up some pointers when you first call them on stream and only performs real filtering when you call the terminal method.
Read more »