Languages
[Edit]
EN

Java 8 - remove empty strings from List

0 points
Created by:
Abul-Emery
457

In this article, we would like to show you how to remove empty strings from List using streams in Java 8.

Quick solution:

List<String> filtered = list.stream().filter(x -> !x.isEmpty()).collect(Collectors.toList());

or 

list.removeIf(String::isEmpty);

 

Practical examples

1. Using stream filter() method

In this example, we use stream filter() method to create a new filtered list, which is the copy of the original list without empty strings.

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


public class Example {

    public static void main(String[] args) throws IOException {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("");
        list.add("C");

        System.out.println("Original list: " + list);  // [A, , C]

        // create filtered copy of the original list
        List<String> filtered = list.stream()
                .filter(x -> !x.isEmpty())
                .collect(Collectors.toList());

        System.out.println("Filtered list: " + filtered);  // [A, C]
    }
}

Output:

Original list: [A, , C]
Filtered list: [A, C]

2. Using removeIf() with method reference

In this example, we use removeIf() method with method reference to remove empty strings from the original list.

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class Example {

    public static void main(String[] args) throws IOException {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("");
        list.add("C");

        System.out.println("Before: " + list);  // [A, , C]

        list.removeIf(String::isEmpty);  // remove empty strings

        System.out.println("After:  " + list);  // [A, C]
    }
}

Output:

Before: [A, , C]
After:  [A, C]

Note:

Solution with the following method reference:

list.removeIf(String::isEmpty);

is equivalent to:

list.removeIf(x -> x.isEmpty());
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join