Java 8 Filter a List with Stream

To filter a List in java before Java 8 requires to iterate through complete list and need us to write many lines of code. After Java 8 filtering a List became so easy. Today I will show how to filter a List before Java 8 and how to filter a list with stream in Java 8.

1. Filter a List before Java 8

package com.codehelp.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListFilterBeforeJava8 {

    public static void main(final String[] args) {

        final List languages = Arrays.asList("Java", "Kotlin", "Python", "Scala", "Swift");
        final List filteredLanguages = new ArrayList<>();

        // filter out the languages starting with S letter
        for (final String language : languages) {
            if (language != null && !language.startsWith("S")) {
                filteredLanguages.add(language);
            }
        }

        for (final String lang : filteredLanguages) {
            System.out.println(lang);    //output: Java, Kotlin, Python
        }
    }
    
}

2. Filter a List with Stream in Java 8

The equivalent example in Java 8, stream.filter() to filter a List, and collect() to convert a stream into a List.

package com.codehelp.java8;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ListFilterInJava {
    public static void main(String[] args) {
        
        final List languages = Arrays.asList("Java", "Kotlin", "Python", "Scala", "Swift");

        // filter out the languages starting with S letter
        final List filteredLanguages = languages.stream()                           // convert list to stream
                                     .filter(lang -> lang!=null && !lang.startsWith("S"))   // filter out language starting with S
                                     .collect(Collectors.toList());                         // collect the output and convert streams to a List

        for (final String lang : filteredLanguages) {
            System.out.println(lang);    //output: Java, Kotlin, Python
        }
        
    }
}

 

References :

1. Java Streams
2. Java Stream Filter
3. Java list iterate with forEach

 

 

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.