Filtering using Java stream

This will be a quick Guide on how to filter a List using Java Stream API which was introduced to Java 8.

To filter a List of Strings without streams you would normally write code like this

public static List filterString(List collection) {
List filteredList = new ArrayList<>();
for (String element : collection) {
if (element.length() < 3) {
filteredList.add(element);
}
}
return filteredList;
}

This Code is not the best to read. Fortunetly we can implement this solution much more elegant with streams

public static List filterList(List collection) {
return collection.stream()
.filter(value -> value.length() < 3) 
.collect(toList()); 
}

Cool isn’t it.

Spread the love