对于中间操作和终端操作的定义,请看《JAVA8 stream接口 中间操作和终端操作》,这篇主要讲述的是stream的count,anyMatch,allMatch,noneMatch操作,我们先看下函数的定义
long count();
boolean anyMatch(Predicate<? super T> predicate);
boolean allMatch(Predicate<? super T> predicate);
boolean noneMatch(Predicate<? super T> predicate);
count方法,跟List接口的size一样,返回的都是这个集合流的元素的长度,不同的是,流是集合的一个高级工厂,中间操作是工厂里的每一道工序,我们对这个流操作完成后,可以进行元素的数量的和;
剩下的三个方法,传入的都是Predicate的函数式接口,接口定义请看《JAVA8 Predicate接口》;
anyMatch表示,判断的条件里,任意一个元素成功,返回true
allMatch表示,判断条件里的元素,所有的都是,返回true
noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
下面,看几个例子
List<String> strs = Arrays.asList("a", "a", "a", "a", "b");
boolean aa = strs.stream().anyMatch(str -> str.equals("a"));
boolean bb = strs.stream().allMatch(str -> str.equals("a"));
boolean cc = strs.stream().noneMatch(str -> str.equals("a"));
long count = strs.stream().filter(str -> str.equals("a")).count();
System.out.println(aa);// TRUE
System.out.println(bb);// FALSE
System.out.println(cc);// FALSE
System.out.println(count);// 4
通过例子可以看到,变量aa的表达式,strs里的元素,任意有“a”,表示true
变量bb的表达式,strs里的元素,全部为“a”,表示true,否则false
变量cc的表达式,strs里的元素,全部不为“a”,表示true,否则false
先看下如下代码
public static void main(String[] args) {
List<String> list = new ArrayList<>();
boolean allMatch = list.stream().allMatch(e -> e.equals("a"));
boolean anyMatch = list.stream().anyMatch(e -> e.equals("a"));
boolean noneMatch = list.stream().noneMatch(e -> e.equals("a"));
System.out.println(allMatch);// true
System.out.println(anyMatch);// false
System.out.println(noneMatch);// true
}
最近,有小伙伴留言说,boolean allMatch = list.stream().allMatch(e -> e.equals(“a”));
当list的为空集合时候,这个返回默认为true;按照实际的业务,理解这个的话,应该为false;然后网上搜索了一下,比较尴尬的是,很多都是抄下我之前的文章,秉承着,严谨的原则,查看了源码,下面是整个分析的过程;
详细看《java8 stream接口终端操作allMatch 当list为空集合的一些思考》