2304 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));
}
}