Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - filter empty string from List not working

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?

like image 213
Alexander Nikolov Avatar asked Nov 15 '16 09:11

Alexander Nikolov


People also ask

How do I check if a String is empty or null in Java 8?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string. isEmpty() || string.

How do I filter a String in Java 8?

In Java 8 and above, use chars() or codePoints() method of String class to get an IntStream of char values from the given sequence. Then call the filter() method of Stream for restricting the char values to match the given predicate.


1 Answers

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);
like image 190
JB Nizet Avatar answered Oct 05 '22 00:10

JB Nizet