如何从 Java 列表中筛选出空字符串值?
假设我们有一个带有空值的字符串列表。这里,在足球之前和壁球之后,我们有空数组元素
List<String> sports = Arrays.asList("","Football", "Cricket", "Tennis", "Squash","", "Fencing", "Rugby");
现在过滤掉空字符串值。首先,我们已使用谓词取反值
Stream<String> stream = sports.stream(); Predicate<String> empty = String::isEmpty; Predicate<String> emptyRev = empty.negate(); stream.filter(emptyRev).collect(Collectors.toList()));
以下是从列表中过滤空字符串值的示例
示例
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { List<String> sports = Arrays.asList("","Football", "Cricket", "Tennis", "Squash","", "Fencing", "Rugby"); System.out.println("List with empty elements..."); for (String res : sports) { System.out.print(res+" "); } Stream<String> stream = sports.stream(); Predicate<String> empty = String::isEmpty; Predicate<String> emptyRev = empty.negate(); System.out.println("
Strings after removing empty array values = "+stream.filter(emptyRev).collect(Collectors.toList())); } }
输出
List with empty elements... Football Cricket Tennis Squash Fencing Rugby Strings after removing empty array values = [Football, Cricket, Tennis, Squash, Fencing, Rugby]
广告