JavaCodingNerd

Java Coding Nerd. This Blog will feature content-rich articles, tutorials and own opinions on variuos programming related topcis.

Java 8, Java Tutorial

How to: Filter a List with Java Stream API

Asynchronus REST-Calls LocalDateTimeConverter

Asynchronus REST-Calls LocalDateTimeConverter

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

Leave a Reply

Theme by Anders Norén