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