Showing posts with label String Filtering. Show all posts
Showing posts with label String Filtering. Show all posts

Saturday, October 27, 2018

Filter Strings Using Stream API in Java


In this article we will learn how to use Java 8 Stream Filter with Example,  I have used String list to filter the names. Stream, A sequence of elements supporting sequential and parallel aggregate operations. Below example will show you how to filter the list with predicate.

StringFilterUsingStream.java

package com.techbyteslearn.tutorial;

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

public class StringFilterUsingStream {

    public static void main(String[] str) {

        List<String> nameList = new ArrayList<String>();

        nameList.add("Roshna");
        nameList.add("Amit Kumar");
        nameList.add("Manoj");
        nameList.add("Neha");
        nameList.add("Rina");
        nameList.add("Ashna");
        nameList.add("Peter");
        nameList.add("Deb Kumar");

        System.out.println("All Names ::");
        nameList.stream().forEach(name -> System.out.println(name));

        // Filter all names ending with "Kumar"
        List<String> filteredList = nameList.stream()
                .filter(name -> name.endsWith("Kumar"))
                .collect(Collectors.toList());

        System.out.println("\nFiltered Names ::");
        filteredList.stream().forEach(name -> System.out.println(name));
    }
}

Output:

All Names :: Roshna Amit Kumar Manoj Neha Rina Ashna Peter Deb Kumar Filtered Names :: Amit Kumar Deb Kumar

I changed the comment from “ends with” to “ending with” and formatted the stream expression for readability. The program logic remains the same.


Hope this will help you. Happy Learning.