Home / JAVA Complete Reference by Examples / Streams / How to filter an List stream using Lambda expression in Java 8 by Example
How to filter an List stream using Lambda expression in Java 8 by Example
2759 views.
package com.learnbyexamples.streams;

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


/*
 * Find number of names which has 4 and 3 characters.
 */
public class E002_ListFilterStream {
    public static void main(String[] args) {
        //Simple list of strings
        List<String> names = new ArrayList<>();
        names.add("Arun");
        names.add("Raja");
        names.add("Kumar");
        names.add("Ram");
        names.add("Siva");
        
        //Convert list into Stream
        Stream<String> namesStream = names.stream();
        
        //Filter 4 Char names gives new stream
        //interface Predicate<T> which has single abstract method - boolean test(T t).
        Stream<String> namesHas4Chrs = namesStream.filter(name -> name.length() == 4);
        
        List<String> filteredNames = namesHas4Chrs.collect(Collectors.toList());
        System.out.println(filteredNames);
        
        //If you want to do in single line.
        List<String> hasThreeChrs = names.stream().filter( name -> name.length() == 3 ).collect(Collectors.toList());
        System.out.println(hasThreeChrs);
    }
}
Output
[Arun, Raja, Siva]
[Ram]
Related Examples
   How to filter an List stream using Lambda expression in Java 8 by Example
   How to filter an Array stream using Lambda expression in Java 8 by Example
   How to filter an Map stream using Lambda expression in Java 8 by Example
   How to use Stream generate method using Lamdba expression in Java 8 Example
   How to read a file line by line using stream in Java 8 by Example
   How to split string into stream in Java 8 by Example
   How to transform stream elements using map in Java 8 by Example
   How to use flatMap stream method in Java 8 by Example
Copyright © 2016 Learn by Examples, All rights reserved