Wednesday, 1 June 2016

Stream.filter() Example in Java 8

Stream.filter() Example in Java 8

The filter is a Stream API method defined as filter(Predicate<? super T> predicate).
The filter method filters the Stream and returns a stream consisting of the elements of this stream that match the given predicate/condition.
Lets see the filter method in action.


Example 1:

The following program will filter all the names starting with 'B'.

package net.codermag.sample.java8;

import java.util.stream.Stream;

public class StreamFilterExample1 {
 
 public static void main(String[] args) {

 Stream<String> dataStream=Stream.of("Bob","Henry","Brad","Wendy"); 
 
 dataStream.filter(x -> x.startsWith("B"))
           .forEach(System.out :: println);
 }
}

Output:

Bob
Brad



Example 2:

Lets see another example.
The following program uses an isOdd() to filter the odd number.

package net.codermag.sample.java8;

import java.util.stream.Stream;

public class StreamFilterExample2 {

public static void main(String[] args) {
 
 Stream<Integer> dataStream=Stream.of(1,2,3,4,5,6); 
 dataStream.filter(x -> isOdd(x))
           .forEach(System.out :: println); 
}

 private static boolean isOdd(Integer x) {
  if (x % 2 == 0)
   return false;
  else
   return true;
 }
}


Output:

1
3
5



Example 3:

Now lets see a little more complex example.
Here we will filter persons based on their age.

A simple Person Class.

package net.codermag.sample.java8;

public class Person {

 private int age;
 private String name;
 
 Person(int age, String name) {
   this.age = age;
   this.name = name;
  }


 public int getAge() {
  return age;
  }
 
 public String getName() {
  return name;
  }

}


Filtering Persons based on age and printing their names.

package net.codermag.sample.java8;

import java.util.stream.Stream;

public class StreamFilterExample3 {
 public static void main(String[] args) {

  Person person1 = new Person(25, "John");
  Person person2 = new Person(45, "Travis");
  Person person3 = new Person(35, "Scott");
  Person person4 = new Person(55, "Wendy");

  Stream<Person> personStream = Stream.of(person1, person2, person3,person4);
  
  personStream.filter(person -> person.getAge() > 40)
              .forEach(person -> System.out.println(person.getName()));

 }
}
Output:

Travis
Wendy


So to conclude the filter() method is a very handy method while working with Streams in Java 8,
as it allows us to filter data based on our needs very easily, quickly and clearly.

Efficiency and Optimizations:
The filter() operation in Stream is an intermediate operation, which returns a lazy stream
and it thereby improves the efficiency as it does not have to process the whole Stream data.

It gains this advantage by breaking after a certain predicate is fulfilled.
Get an idea of Lazy Streams.
LEARN MORE about it here : "LAZY STREAMS in Java 8"