Java Stream filter()

Stream filter() method

This method accepts a predicate and filters the stream based on the condition provided in the predicate.

We can also use a lambda expression in place of a predicate.

Since it returns a stream, we need a terminal operation like count() or collect() to process it.

In below example, the filter() method acts on the stream of country names and only chooses the names starting with “A”.
 
stream filter operation

This stream is then used by the count() method to count the strings.
 

Example : Filtering Country names that start with “A”

package com.topjavatutorial.java8examples;

import java.util.Arrays;
import java.util.List;

public class StreamOperations {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    
    List<String> countries = Arrays.asList("Australia","Brazil", "China","Denmark","England","France","Germany");
    
    //Count country names starting with A
    
    long count = countries.stream().filter(countryName -> countryName.startsWith("A")).count();
    
    System.out.println("Country names starting with A = " + count);

  }

}


 
Running this program will produce output :

Country names starting with A = 1
 

Example : Filtering Strings that start with a Number

Stream.of("123", "1bc", "c2e", "fg3")
    .filter(str -> Character.isDigit(str.charAt(0)))
    .forEach(System.out::println);

Output:

123
1bc
 

Example : Filter sub-directories in the current directory

try {
  Files.list(Paths.get(".")).filter(Files::isDirectory)
          .forEach(System.out::println);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags