Stream 流是简化集合和数组操作的一种编程方式,使得集合和数组的操作像水流一样流畅。
更多参考:https://www.yuque.com/zhangshuaiyin/java/java-8-stream-api
下面通过原理 +实战 的方式了解 Stream 的用法。
// 1. 集合Collection<String> list=newArrayList<>();Stream<String> ss= list.stream();// 2. 数组String[] arrs=newString[]{"Java","Python","C"};Stream<String> arrs1=Arrays.stream(arrs);Stream<String> arrs2=Stream.of(arrs);
中间操作(intermediate):通过一系列中间(Intermediate)方法,对数据集进行过滤、检索等数据集的再次处理。
终止操作(Terminal):通过最终(terminal)方法完成对数据集中元素的处理。
短路操作(Short-circuiting):指遇到某些符合条件的元素就可以得到最终结果,如 A || B,只要A为true,则无需判断B的结果。
Stream 中间操作不会自己启动,所以测试中都会加上 forEach 终止操作来启动 Stream 流的执行。
List<String> list=Arrays.asList("Java","","Spring","Mysql","Python","","C++");
【中间操作】过滤元素,筛选 Stream 流中符合条件的元素,作为流返回。
Stream<T>filter(Predicate<?superT> predicate);
list.stream().filter(String::isEmpty).forEach(System.out::println);
【中间操作】对 Stream 流中的元素执行指定操作后映射为新的值流返回(会改变之前的集合元素),相当于加工。
<R>Stream<R>map(Function<?superT,?extendsR> mapper);
list.stream().map(String::toUpperCase).forEach(System.out::println);
【中间操作】返回一个由该流的元素组成的流,另外在每个元素上执行提供的操作,因为元素从结果流中被消耗。(Consumer 没有返回值,不会改变原来 Stream 流中的值)
Stream<T>peek(Consumer<?superT> action);
@apiNote This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:
此方法的存在主要是为了支持调试,您希望在其中查看元素流经管道中的某个点时的情况:
list.stream().filter(e-> e.length()>3).peek(e->System.out.println("Filtered value: "+ e)).map(String::toUpperCase).peek(e->System.out.println("Mapped value: "+ e)).forEach(System.out::println);
【短路有状态中间操作】截取 Stream 流中前 maxSize 个 元素。
Stream<T>limit(long maxSize);
list.stream().limit(4).forEach(System.out::println);
【有状态中间操作】在丢弃流的前 n 元素后,返回由该流的其余元素组成的流。 如果此流包含少于 n 元素,则将返回一个空流。
Stream<T>skip(long n);
list.stream().skip(4).forEach(System.out::println);
【有状态中间操作】返回由该流的不同元素(根据Object.equals(Object) )组成的流。
Stream<T>distinct();
list.stream().distinct().forEach(System.out::println);
【有状态中间操作】返回由该流的元素组成的流,按自然顺序排序。
Stream<T>sorted();Stream<T>sorted(Comparator<?superT> comparator);
list.stream().sorted().forEach(System.out::println);// 还可以实现 Comparator 接口来自定义排序规则 list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
【终止操作】遍历操作,依次遍历 Stream 流中的元素,并执行给定的行为。
voidforEach(Consumer<?superT> action);
list.stream().forEach(System.out::println);// 集合只遍历可简写为 Collection 自带的 forEach() 方法// list.forEach(System.out::println);
【终止操作】返回一个包含此流元素的数组。
Object[]toArray();
list.stream().toArray();// 对于集合可简写为 Collection 自带的 toArray() 方法// list.toArray();
【终止操作】返回 Stream 流中最小/最大的元素
Optional<T>min(Comparator<?superT> comparator);Optional<T>max(Comparator<?superT> comparator);
Optional<String> min= list.stream().min(Comparator.naturalOrder());System.out.println(min.get());Optional<String> max= list.stream().max(Comparator.naturalOrder());System.out.println(max.get());
【终止操作】返回此流中元素的计数。
longcount();
long size= list.stream().count();// 对于集合可简写为 Collection 自带的 size() 方法// list.size();
【终止操作】使用提供的标识值和关联累积函数对该流的元素执行归约,并返回归约后的值。
Treduce(T identity,BinaryOperator<T> accumulator);Optional<T>reduce(BinaryOperator<T> accumulator);<U>Ureduce(U identity,BiFunction<U,?superT,U> accumulator,BinaryOperator<U> combiner);
String result= list.stream().reduce("",(s1, s2)-> s1+ s2);// JavaSpringMysqlPythonC++Optional<String> result= list.stream().reduce((s1, s2)-> s1+ s2);
【终止操作】将 Stream 流转换为其他形式,该操作主要作为进行中间操作后的可变规约操作。
<R>Rcollect(Supplier<R> supplier,BiConsumer<R,?superT> accumulator,BiConsumer<R,R> combiner);<R,A>Rcollect(Collector<?superT,A,R> collector);
list.stream().collect(Collectors.toSet());// 连接字符串// String result = list.stream().collect(Collectors.joining("-"));
【短路终止操作】如果流的任何元素与提供的 断言 匹配,则为 true ,否则为 false。
booleananyMatch(Predicate<?superT> predicate);
boolean result= list.stream().anyMatch(s-> s.length()>6)// false
【短路终止操作】Stream 流中所有元素都与提供的 断言匹配,则为 ture,否则为 false。
booleanallMatch(Predicate<?superT> predicate);
boolean result= list.stream().allMatch(s-> s.length()<=6);// true
【短路终止操作】Stream 流中的所有元素都与提供的 断言 不匹配,则返回 true,否则为 false。
booleannoneMatch(Predicate<?superT> predicate);
boolean result= list.stream().noneMatch(s-> s.length()>6);// true
【短路终止操作】返回 Stream 流中第一个元素。
Optional<T>findFirst();
Optional<String> first= list.stream().findFirst();String result= first.get();// Java
【短路终止操作】返回 Stream 流中第一个元素。
Optional<T>findAny();
Optional<String> first= list.stream().findAny();String result= first.get();// JavaOptional<String> first= list.parallelStream().findAny();String result= first.get();// Python