使用 Stream 类的搜索方法搜索数据,包括 findFirst、 findAny、 anyMatch、 allMatch、 noneMatch。
查找和匹配
有一组数据时,搜索是一种常见的操作。Stream API 有两种类型的搜索操作。
因为其返回类型不为Stream类型,所以为终止操作
以Find开始的方法
Optional<T> findAny()
Optional<T> findFirst()
如果stream为空kennel无法找到元素,因此返回Optional类
以Match结尾的方法
boolean allMatch(Predicate<? super T> predicate)
boolean anyMatch(Predicate<? super T> predicate)
boolean noneMatch(Predicate<? super T> predicate)
如果某个元素与给定的谓词匹配,那么它们将返回一个布尔值
findAny() and findFirst()
- 它们返回在流中找到的第一个元素
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
stream.findFirst()
.ifPresent(System.out::println); // 1
IntStream stream2 = IntStream.of(1, 2, 3, 4, 5, 6, 7);
stream2.findAny()
.ifPresent(System.out::println); // 1
- 如果stream是空的,返回一个空的 Optional
Stream<String> stream = Stream.empty();
System.out.println(
stream.findAny().isPresent()
); // false
- 如何抉择
并行情况下,为了性能,满足逻辑的情况下,使用findAny()
anyMatch ()、 allMatch ()和 noneMatch ()
anyMatch ()
- 如果流中有任何一个元素与给定的谓词匹配,则 anyMatch ()返回 true:
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream.anyMatch(i -> i%3 == 0)
); // true
- 如果流是空的或者没有匹配的元素,这个方法返回 false:
IntStream stream = IntStream.empty();
System.out.println(
stream.anyMatch(i -> i%3 == 0)
); // false
IntStream stream2 = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream2.anyMatch(i -> i%10 == 0)
); // false
allMatch()
- Stream中的所有元素都匹配给定的谓词时,allMatch ()才返回 true:
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream.allMatch(i -> i > 0)
); // true
IntStream stream2 = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream2.allMatch(i -> i%3 == 0)
); // false
- stream是空的,这个方法返回 TRUE 而不计算谓词
IntStream stream = IntStream.empty();
System.out.println(
stream.allMatch(i -> i%3 == 0)
); // true
noneMatch ()
与 allMatch ()相反
- 如果流中的元素都不匹配给定的谓词,则返回 true
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream.noneMatch(i -> i > 0)
); // false
IntStream stream2 = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream2.noneMatch(i -> i%3 == 0)
); // false
IntStream stream3 = IntStream.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(
stream3.noneMatch(i -> i > 10)
); // true
- stream流是空的,这个方法还是返回 TRUE
短路特性
所有这些操作都使用类似于 & & 和 | | 操作符的短路。
计算一旦找到结果就停止
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
boolean b = stream
.filter(i -> {
System.out.println("Filter:" + i);
return i % 2 == 0; })
.allMatch(i -> {
System.out.println("AllMatch:" + i);
return i < 3;
});
System.out.println(b);
结论
- stream上的操作不是按顺序计算的(在这种情况下,首先过滤所有元素,然后计算是否所有元素都匹配 allMatch ()的谓词)
- 元素通过filter,allMatch就会被执行
- 短路的行,allMatch计算得到的结果中第一个不为true,就会停止,不会处理其他元素,直接返回结果
对于某些操作,不需要处理整个流。流操作不是按顺序执行的
总结
- 这两种类型都是终端操作。
- 如果stream流为空,则allMatch()和noneMatch()都返回true。
- 所有这些操作都是短路的,一旦找到结果,stream流计算操作就会停止。
Comments | 0 条评论