Java stream使用与执行原理

2024-09-08 04:28
文章标签 java 使用 原理 执行 stream

本文主要是介绍Java stream使用与执行原理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

stream简介

Stream: A sequence of elements supporting sequential and parallel aggregate operations

stream为sequential即单线程串行操作,parallelStream支持并行操作,本文只讨论sequential的stream。

stream常用操作

    @Datastatic class Course {private Long number;private LocalDateTime beginTime;private List<Long> studentIds;}public void streamOperations(List<Course> courses) {// 映射并去重List<Long> courseNumbers = courses.stream().filter(Objects::nonNull).map(Course::getNumber).distinct().collect(Collectors.toList());// 先按开始时间排序后按number排序List<Course> sortedCourses = courses.stream().sorted(Comparator.comparing(Course::getBeginTime).thenComparing(Course::getNumber)).collect(Collectors.toList());// 根据number组成map, 如果有相同的number会抛异常Map<Long, Course> num2Lesson1 = courses.stream().collect(Collectors.toMap(Course::getNumber, Function.identity()));// 根据number组成map, 如果有相同的number会执行降级逻辑Map<Long, Course> num2Lesson2 = courses.stream().collect(Collectors.toMap(Course::getNumber, Function.identity(), (v1, v2) -> v1));// 根据number聚合Map<Long, List<Course>> num2Lessons = courses.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(Course::getNumber));// 根据number聚合某个字段Map<Long, List<LocalDateTime>> number2BeginTimes = courses.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(Course::getNumber,Collectors.mapping(Course::getBeginTime, Collectors.toList())));// 根据number找到number下最大beginTime的CourseMap<Long, Optional<Course>> number2MaxBeginTimeCourse = courses.stream().filter(r -> Objects.nonNull(r.getBeginTime())).collect(Collectors.groupingBy(Course::getNumber, Collectors.maxBy(Comparator.comparing(Course::getBeginTime))));// 获取course下所有的studentIdList<Long> allStudentIds = courses.stream().map(Course::getStudentIds).flatMap(Collection::stream).distinct().collect(Collectors.toList());}

stream原理

基本原理

        list.stream().filter(Objects::nonNull).map(World::toString).distinct().collect(Collectors.toList());

以上面的处理为例,分别经过了过滤->映射->去重->聚合三个操作,在stream内部会通过一个链表将这三个操作联系起来,一个操作被称为一个stage(或pipeline),每个stage会指向上下游的stagesourceStage(即哨兵头节点),如下图所示:

在这里插入图片描述

对应的在AbstractPipeline类中有三个字段分别引用链表上下游节点和链表的哨兵头节点:

abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>extends PipelineHelper<E_OUT> implements BaseStream<E_OUT, S> {// Backlink to the head of the pipeline chain (self if this is the source stage).private final AbstractPipeline sourceStage;// The "upstream" pipeline, or null if this is the source stage.private final AbstractPipeline previousStage;  // The next stage in the pipeline, or null if this is the last stage. Effectively final at the point of linking to the next pipeline.      private AbstractPipeline nextStage;  ...    
}

stage可分为3类(可以在各个Reference类中找到下面3个内部类):

  • Header: 哨兵头节点,用户无需感知
  • StatelessOp: 无状态stage,如过滤
  • StatefulOp: 有状态stage,如聚合

对应的在ReferencePipeline中有3个内部类:

abstract class ReferencePipeline<P_IN, P_OUT>extends AbstractPipeline<P_IN, P_OUT, Stream<P_OUT>>implements Stream<P_OUT>  {static class Head<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> {...}abstract static class StatelessOp<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> {...}abstract static class StatefulOp<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> {...}  ...     
}

以上提到的三种名词:pipeline,stage,op 都是指代链表里的一个操作节点,即 pipeline == stage == op,类似一个生物学人具有多个社会学身份。

再来看看代码实现,其uml类图如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
Java对BaseStream接口的实现是 AbstractPipelineBaseStream可分为基于引用类型和基于基础类型,其中基于引用类型实现为ReferencePipleline,基于数值基础类型分别有实现LongPiplelineIntPiplelineDoublePipleline

pipeline中封装了stream sourceintermediate operations,一个pipeline代表一次操作,比如过滤、去重等,当 pipeline 被引用时则称为stage,多个stage可以通过Fluent Api组装起来实现流式处理,组装的过程即是构建一个链表的过程。

当我们调用一个集合的stream()方法时,会调用StreamSupport#stream方法构造一个header pipeline:

public interface Collection<E> extends Iterable<E> {...default Stream<E> stream() {// 传入Collection自定义个Spliterator,返回一个 header pipelinereturn StreamSupport.stream(spliterator(), false);}...// Collection自定义的Spliteratordefault Spliterator<E> spliterator() {return Spliterators.spliterator(this, 0);}...
}public final class StreamSupport {...// 生成 header pipelinepublic static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) {Objects.requireNonNull(spliterator);return new ReferencePipeline.Head<>(spliterator,StreamOpFlag.fromCharacteristics(spliterator),parallel);}...
}
java.util.Spliterator

两个问题:

  1. Spliterator是干嘛的?
  2. stream为什么需要Spliterator?

An object for traversing and partitioning elements of a source.

可以看到Spliterator支持对数据进行遍历和分割,对应的在接口中有tryAdvance + forEachRemaining用于遍历,有trySplit支持分割。

trySplit方法返回的是Spliterator,所以Spliterator是一种类似细胞分裂的方式执行,对一个ArrayList进行分割:

        List<Integer> list = new ArrayList<>();for (int i = 1; i <= 5; i++) {list.add(i);}Spliterator<Integer> sourceSpliterator = list.spliterator();Assertions.assertEquals(5, sourceSpliterator.estimateSize());// 执行一次,输出1,剩下2345四个元素可分割和遍历sourceSpliterator.tryAdvance(i -> Assertions.assertEquals(1, i));Assertions.assertEquals(4, sourceSpliterator.estimateSize());Spliterator<Integer> subSpliterator1 = sourceSpliterator.trySplit();// 2 3Assertions.assertEquals(2, sourceSpliterator.estimateSize());// 4 5Assertions.assertEquals(2, subSpliterator1.estimateSize());List<Integer> list2 = new ArrayList<>();list2.add(1);// 只有一个元素时进行split,此时spliterator1==nullSpliterator<Integer> spliterator1 = list2.spliterator().trySplit();Assertions.assertNull(spliterator1);

Spliterator只对未遍历过的元素(未被tryAdvance执行到且未执行forEachRemaining)执行trySplit,如果没有trySplit返回null, 同样stream流只运行执行一次。

同时Spliterator有以下特性,可以包含多个:

  • ORDERED: 遍历和分割保证顺序
  • DISTINCT: 非重复
  • SORTED: 遍历和分割时以一种顺序执行,通过getComparator方法提供自定义比较器
  • SIZED: estimateSize放回返回固定值
  • SUBSIZED: trySplit之后所有的Spliterator同时支持SIZED和SUBSIZED特性
  • IMMUTABLE: 遍历和分割的对象不能有结构变更
  • CONCURRENT: 支持多线程安全遍历和分割

所有特性以bitset的方式记录在一个int类型值中,通过characteristics方法获取。

那么为什么stream要用Spliterator呢?

Spliterator是并行流(Parallel Stream)背后的关键机制。当调用集合的parallelStream()方法时,该方法内部会创建一个Spliterator来遍历和分割集合中的元素。然后,Java的并行框架(如ForkJoinPool)会利用这些Spliterator来分配任务给多个线程,以实现并行处理。

java.util.stream.Sink

stream的操作都在该接口中实现

An extension of Consumer used to conduct values through the stages of a stream pipeline,
with additional methods to manage size information, control flow, etc.

通常使用内部抽象类ChainedReference构建一个Sink链,ChainedReference 中指向链条的下一个Sink
stream支持多元素操作如sorted和单元素操作如map,如何组合这两种操作呢?stream即是通过Sink接口实现。

Sink包含三个主要接口:

interface Sink<T> extends Consumer<T> {// 调用该接口表示stage开始接收数据,size表示要接受的数据个数,-1表示未知或无限制default void begin(long size) {}// 调用该接口表示stage数据接受完毕,当需要操作所有数据时,可在这里操作,比如sorted就在这里做排序default void end() {}// 调用该接口表示stage开始操作单个数据default void accept(int value)...
}

注意以上接口都是default,如果子接口(如TerminalSink)没实现表示默认不做操作。

以以下stream流为例:


list = [3,2,5]list.stream().filter(Objects::nonNull).map(i -> i + "hello").distinct().sorted().forEach(System.out::println);

当我们调用list.stream.filter.map.distinct.sorted.collect时,
会首先正向构建一个stage操作双向链表,即filter <-> map <-> distinct <-> sorted <-> collect
最后在链接TerminalOp类型的stage时(这里是collect)会调用AbstractPipeline#wrapSink方法构建Sink单向链表,Sink单向链表的指向顺序也是filter -> map -> distinct -> sorted -> collect,但其构建顺序是反向的,即collect -> sorted -> distinct -> map -> filter,如下图所示:

在这里插入图片描述

代码如下:

abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>extends PipelineHelper<E_OUT> implements BaseStream<E_OUT, S> {...// .stream()执行时表示中间操作stage的个数// .parallelStream()执行时表示前面有状态的中间操作个数,因为有状态依赖的必须sequential执行private int depth;@Overridefinal <P_IN> Sink<P_IN> wrapSink(Sink<E_OUT> sink) {Objects.requireNonNull(sink);for ( @SuppressWarnings("rawtypes") AbstractPipeline p=AbstractPipeline.this; p.depth > 0; // 前面的stagep=p.previousStage) {sink = p.opWrapSink(p.previousStage.combinedFlags, sink);}return (Sink<P_IN>) sink;}...    
}

来模拟[3,2,5]作为输入时的stream流程:
在这里插入图片描述

这篇关于Java stream使用与执行原理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147108

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数