stackUnderflow stackUnderflow - 21 days ago 8
Java Question

Java 8 - filter empty string from List not working

I would like to remove an empty String from List of Strings.

Here is what I tried, using the stream API:

list.stream().filter(item-> item.isEmpty()).collect(Collectors.toList());


and the empty string is still present in the list. What am I missing ?

Answer

filter() keeps the elements that match the predicate. Soyou need the inverse predicate:

list.stream().filter(item-> !item.isEmpty()).collect(Collectors.toList());

This will also not modify the original list. It will create a filtered copy of the original list. So you need

list = list.stream().filter(item-> !item.isEmpty()).collect(Collectors.toList());

If you want to modify the original list, you should use

list.removeIf(item -> item.isEmpty());

or simply

list.removeIf(String::isEmpty);
Comments