当前位置:网站首页>Stream API
Stream API
2022-08-04 05:31:00 【Louzen】
最近在项目中看到了Stream,之前我对它只是泛泛了解,觉得写、看都挺麻烦,不如传统的集合处理方式更加直观、可读性强,但上手敲过后发现Stream原来很方便,颠覆了我对它的看法。
Stream 简介
顾名思义,Stream是“流”的意思,它将 集合 类型数据以流的形式进行处理,把数据想想成河流,举个例子,我可以自上游到下游按顺序安排上洗脸、洗衣服、洗jio三个过程,数据按序流过了这三个过程,最后出来的就是洗jio水
这里要与IOStream进行区分,不要搞混了,IOStream是对字符处理的流,Stream是对集合数据处理
Stream 优势
个人认为,Stream优势的根源就在于 “流” 的数据处理思想,方法的返回值是它自身,这样就可以链式地调用处理方法,让对数据的操作化为一个连续的过程
- 化繁为简
对 List 的一系列操作可以串在一起、一气呵成,相比之下,传统的对List的操作会很麻烦,比如需要将List<User>中User对象中的name取出来组成新的List,传统做法对比Stream如下:
传统:
List<User> userList = UserListFactory.get();
ArrayList<String> nameList = new ArrayList<>();
for(User user : userList) {
nameList.add(user.getName());
}
Stream:
List<String> nameList = UserListFactory.get().stream()// userList转成stream
.map(user -> user.getName())//userList中的每个user对象对应另一个元素(这里是name)
.collect(Collectors.toList());// Stream转List
- 可读性强
当然,在不懂Stream使用规则的情况下,Stream读起来会有一定难度,但是在熟悉了Stream的规则后,Stream对List的一系列操作会让你很直观地看懂我对List做了哪些操作以及操作的顺序 - 代码精简
如上面的例子,传统方式在userList变nameList的过程中,代码是不连续的,是会产生中间变量与中间结果的,而Stream一个语句就做到了。
如果场景更复杂些,比如要将List转换为Map再转换为List,中间还夹杂着对属性的操作,传统方式的代码量会很多,并且会产生更多无用的中间产物,而Stream一个语句就可以搞得定
Stream 使用
java.util.Collection接口中有stream()方法,可以得到Stream对象,List、Set、Queue实现了Collection接口,有stream方法的实现,而Map却没有这个方法,但,stream流最后可以以Map的形式输出
- forEach
顾名思义,就是迭代集合中的元素,同时对元素进行处理,注意,此方法无返回值。下面的例子就是将userList中每个user元素的年龄都做+1操作
List<User> userList = UserListFactory.get();
userList.stream().forEach(user -> user.setAge(user.getAge() + 1));
- map
此方法,是将userList中原本的user元素映射为另一种数据。样例如下,注意,List转为Stream流再经过映射操作再转为List后,是List,集合中元素的数据类型要符合映射结果的数据类型
List<User> userList = UserListFactory.get();
List<Integer> ageList = userList.stream()
.map(user -> user.getAge() + 1)
.collect(Collectors.toList());
- filter
顾名思义,这个方法的作用是筛选,里面是一个表达式,集合中元素放入表达式中,结果为true则该元素通过,为false则该元素被拦截下来
List<User> userList = UserListFactory.get();
List<User> userList2 = userList.stream()
.filter(user -> user.getAge() > 18)
.collect(Collectors.toList());
- collect
看了上面的代码,你肯定有一个疑问,为什么每个代码示例后面都有collect方法?集合类型在使用Stream()方法后会转成Stream流类型,collect方法是将Stream流类型格式化为指定格式的数据类型,目前为止我在项目中较常用的是转为List或Map
注意:下面第一种转Map的方式存在bug!键值都不可以为null,否则会报空指针异常,如果不提前知道这里埋着雷调试代码时就会以泪洗面。。避坑!感兴趣的自行百度“Collectors.toMap空指针”或“Stream List转Map的坑”或自查源码,暂时就不展开说了;采用第二种转Map方式无忧,第二种方式实际就是自己定义Collectors.toMap方法
Stream转List:
像上面一样,stream.collect(Collectors.toList())即可
Strea转Map方式一(有bug):
List<User> userList = UserListFactory.get();
Map<String, User> userMap = userList.stream()
.collect(Collectors.toMap(User::getName, user -> user));
Stream转Map方式二:
List<User> userList = UserListFactory.get();
HashMap<Object, Object> userMap = userList.stream()
.collect(
HashMap::new,
(map, user) -> map.put(user.getName(), user),
HashMap::putAll);
- limit
- sorted
- flatMap
…未完待续 2021.02.04
边栏推荐
- 学习资料re-id
- 【五一专属】阿里云ECS大测评#五一专属|向所有热爱分享的“技术劳动者”致敬#
- 关于DG(域泛化)领域的PCL方法的代码实例
- MNIST手写数字识别 —— Lenet-5首个商用级别卷积神经网络
- Golang环境变量设置(二)--GOMODULE&GOPROXY
- MNIST handwritten digit recognition - based on Mindspore to quickly build a perceptron to achieve ten categories
- MOOSE平台官方第二个例子分析——关于创建Kernel,求解对流扩散方程
- 浅谈游戏音效测试点
- Golang environment variable settings (2)--GOMODULE & GOPROXY
- Implementation of CAS lock-free queue
猜你喜欢
YOLOV4流程图(方便理解)
【论文阅读】Exploring Spatial Significance via Hybrid Pyramidal Graph Network for Vehicle Re-identificatio
No matching function for call to 'RCTBridgeModuleNameForClass'
打金?工作室?账号被封?游戏灰黑产离我们有多近
Copy攻城狮信手”粘“来 AI 对对联
MNIST手写数字识别 —— 从零构建感知机实现二分类
【论文阅读】Anchor-Free Person Search
腾讯、网易纷纷出手,火到出圈的元宇宙到底是个啥?
Copy攻城狮的年度之“战”|回顾2020
The second official example analysis of the MOOSE platform - about creating a Kernel and solving the convection-diffusion equation
随机推荐
MNIST手写数字识别 —— 基于Mindspore快速构建感知机实现十分类
第二章 STA相关概念
[Deep Learning Diary] Day 1: Hello world, Hello CNN MNIST
集合---ArrayList的底层
LeetCode_Nov_5th_Week
counting cycle
浅谈游戏音效测试点
MNIST手写数字识别 —— 从二分类到十分类
LeetCode_Dec_3rd_Week
How to get started with MOOSE platform - an example of how to run the official tutorial
[CV-Learning] Linear Classifier (SVM Basics)
YOLOV4流程图(方便理解)
【论文阅读】TransReID: Transformer-based Object Re-Identification
【代码学习】
Cut the hit pro subtitles export of essays
剪映专业版字幕导出随笔
MNIST手写数字识别 —— Lenet-5首个商用级别卷积神经网络
AWS使用EC2降低DeepRacer的训练成本:DeepRacer-for-cloud的实践操作
Rules.make-适合在编辑模式下看
Tencent and NetEase have taken action one after another. What is the metaverse that is so popular that it is out of the circle?