Java 8 - filter empty string from List not working

Alexander Nikolov :

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

Here is what I tried, using the stream API:

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

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

JB Nizet :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=455286&siteId=1