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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With