我希望使用一个以终端操作结束的单流链获得一个假值。
但是,我发现由于allMatch操作的设计,它在处理空流时将返回true。
例如,以下代码返回真,因为过滤后的流在管道中为空。
List<String> list = Arrays.asList("abc", "efg", "hij");
boolean isAllStartsWith1 = list.stream().filter(s-> s.endsWith("x")).allMatch(s->s.startsWith("1"));
System.out.println(isAllStartsWith1);
为了获得预期的结果(false),我需要将流收集到一个临时列表中,并添加额外的检查,以确认在传递到allMatch操作进行最终处理之前是否为空。这使得整个过程看起来非常笨重,是否有更优雅的解决方案来解决这个问题?
List<String> list = Arrays.asList("abc", "efg", "hij");
List<String> filteredList = list.stream().filter(s-> s.endsWith("x")).collect(Collectors.toList());
boolean isAllStartsWith1 = !filteredList.isEmpty() && filteredList.stream().allMatch(s->s.startsWith("1"));
System.out.println(isAllStartsWith1);
发布于 2022-04-18 15:25:59
如果结果大于0,则可以使用.count()
计数返回true,否则为false。
System.out.println(list.stream().filter(s -> s.endsWith("x")).count() > 0);
https://stackoverflow.com/questions/71913434
复制相似问题