How to filter empty string values from a Java List?


Let’s say we have a String List with an empty value. Here, we have empty array elements before Football and after Squash:

List<String> sports = Arrays.asList("","Football", "Cricket", "Tennis", "Squash","", "Fencing", "Rugby");

Now filter the empty string values. At first, we have used Predicate to negate values:

Stream<String> stream = sports.stream();
Predicate<String> empty = String::isEmpty;
Predicate<String> emptyRev = empty.negate();
stream.filter(emptyRev).collect(Collectors.toList()));

The following is an example to filter empty string values from a List:

Example

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      List<String> sports = Arrays.asList("","Football", "Cricket", "Tennis", "Squash","", "Fencing", "Rugby");
      System.out.println("List with empty elements...");
      for (String res : sports)
      {
         System.out.print(res+" ");
      }
      Stream<String> stream = sports.stream();
      Predicate<String> empty = String::isEmpty;
      Predicate<String> emptyRev = empty.negate();
      System.out.println("

Strings after removing empty array values = "+stream.filter(emptyRev).collect(Collectors.toList()));    } }

Output

List with empty elements...
Football Cricket Tennis Squash Fencing Rugby
Strings after removing empty array values = [Football, Cricket, Tennis, Squash, Fencing, Rugby]

Updated on: 30-Jul-2019

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements