假设我们有一个带有空值的字符串列表。在这里,在Football之前和Squash之后,我们有空的数组元素:
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("\n\nStrings 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]