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

import java.util.Arrays;
import java.util.stream.Stream;

/*
 * Find number of names which has 4 and 3 characters.
 */
public class E001_FilterStream {
    public static void main(String[] args) {
        //Simple array of strings
        String[] names = {"Arun","Raja","Kumar","Ram","Siva"};
        
        //Convert array into Stream
        Stream<String> namesStream = Stream.of(names);
        
        //Filter 4 Char names into new stream
        //interface Predicate<T> which has single abstract method - boolean test(T t).
        Stream<String> namesHas4Chrs = namesStream.filter(name -> name.length() == 4);
        
        String[] filteredNames = namesHas4Chrs.toArray(size -> new String[size]);
        System.out.println(Arrays.toString(filteredNames));
        
        //If you want to do in single line.
        String[] hasThreeChrs = Stream.of(names).filter( name -> name.length() == 3 ).toArray( size -> new String[size] );
        System.out.println(Arrays.toString(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