stackUnderflow stackUnderflow - 4 months ago 24
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:> item.isEmpty()).collect(Collectors.toList());

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


filter() keeps the elements that match the predicate. Soyou need the inverse predicate:> !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 => !item.isEmpty()).collect(Collectors.toList());

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

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

or simply