当前位置:网站首页>Stream API
Stream API
2022-08-04 06:43:00 【Louzen】
Saw it in a project recentlyStream,I only had a general understanding of it before,觉得写、It looks troublesome,Not as intuitive as the traditional way of dealing with collections、可读性强,But after knocking on it, I found itStreamIt turned out to be very convenient,subverted my view of it.
Stream 简介
顾名思义,Stream是“流”的意思,它将 集合 Type data is processed as a stream,Think of data as a river,举个例子,I can arrange to wash my face in order from upstream to downstream、洗衣服、洗jio三个过程,Data flows through these three processes sequentially,The last thing to do is washjio水
这里要与IOStream进行区分,不要搞混了,IOStreamis a stream for character processing,StreamIt is a collection of data processing
Stream 优势
个人认为,StreamThat's where the advantage comes from “流” data processing ideas,The return value of a method is itself,This makes it possible to chain calls to handler methods,Let the manipulation of data become a continuous process
- 化繁为简
对 List A series of operations can be chained together、一气呵成,相比之下,传统的对Listoperation will be troublesome,比如需要将List<User>中User对象中的nameTake it out to make a new oneList,传统做法对比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中的每个userAn object corresponds to another element(这里是name)
.collect(Collectors.toList());// Stream转List
- 可读性强
当然,在不懂Streamusing the rules,StreamIt will be difficult to read,但是在熟悉了Stream的规则后,Stream对ListA series of operations will make you intuitively understand what I am rightListWhat operations were done and in what order - 代码精简
如上面的例子,传统方式在userList变nameList的过程中,The code is discontinuous,It will produce intermediate variables and intermediate results,而StreamOne sentence does it.
If the scene is more complicated,比如要将List转换为Map再转换为List,There are also operations on properties in the middle,The traditional way would be a lot of code,And will produce more useless intermediates,而StreamOne sentence can do it
Stream 使用
java.util.Collection接口中有stream()方法,可以得到Stream对象,List、Set、Queue实现了Collection接口,有stream方法的实现,而Map却没有这个方法,但,streamThe stream can finally be Map的形式输出
- forEach
顾名思义,is to iterate over the elements in the collection,Elements are processed at the same time,注意,此方法无返回值.下面的例子就是将userList中每个userThe age of the elements all do+1操作
List<User> userList = UserListFactory.get();
userList.stream().forEach(user -> user.setAge(user.getAge() + 1));
- map
此方法,是将userList中原本的userElements map to another kind of data.样例如下,注意,List转为StreamThe stream is then converted to by a mapping operationList后,是List,The data type of the elements in the collection must match the data type of the mapping result
List<User> userList = UserListFactory.get();
List<Integer> ageList = userList.stream()
.map(user -> user.getAge() + 1)
.collect(Collectors.toList());
- filter
顾名思义,The function of this method is to filter,里面是一个表达式,The elements of the collection are put into the expression,结果为truethen the element passes,为falsethen the element is blocked
List<User> userList = UserListFactory.get();
List<User> userList2 = userList.stream()
.filter(user -> user.getAge() > 18)
.collect(Collectors.toList());
- collect
看了上面的代码,你肯定有一个疑问,Why is there after every code examplecollect方法?Collection types are in useStream()method will be converted into Stream流类型,collect方法是将StreamThe stream type is formatted as the data type of the specified format,So far, the most commonly used in my project is to convertList或Map
注意:The first turn belowMap的方式存在bug!None of the key values are allowednull,否则会报空指针异常,If you don't know in advance that there is a mine buried here to debug the code, you will wash your face in tears..避坑!感兴趣的自行百度“Collectors.toMap空指针”或“Stream List转Map的坑”Or check the source code yourself,I won't start talking about it for the time being;Use the second turnMapWorry-free way,The second way is actually to define it yourselfCollectors.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
边栏推荐
猜你喜欢
随机推荐
vs2017 redist 下载地址
Detailed steps to install MySQL
LeetCode_Nov_1st_Week
MySQL存储过程学习笔记(基于8.0)
用PPAPI插件技术在Web上显示会议视频、桌面、PPT等
arm learning-1-development board
IP 核之 MMCM/PLL 实验
结构体传参-C语言
基于asp.net的法律援助平台的设计与实现(附项目链接)
Design and implementation of legal aid platform based on asp.net (with project link)
IEEE802.X protocol suite
strlen 转义字符
An abstract class, internal classes and interfaces
Shell脚本执行的三种方式
指针运算相关面试题详解【C语言】
clssloader与双亲委派
理想的生活
[Daily Office][Miscellaneous][vscode]tab space
counting cycle
【HIT-SC-MEMO2】哈工大2022软件构造 复习笔记2