java8流式操作

简介:Stream 中文称为 “流”,通过将集合转换为这么一种叫做 “流” 的元素序列,通过声明性方式,能够对集合中的每个元素进行一系列并行或串行的流水线操作。

操作分类:

.stream()
stream()把一个源数据,可以是集合,数组,I/O channel, 产生器generator 等,转化成流

常见流操作API

中间操作

.filter()
filter()方法用于通过设置的条件过滤出元素
.map()
map()用于映射每个元素到对应的结果
.sorted()
sorted()用于对流进行排序
distinct():去除重复的元素

終端操作:

forEach():遍历每个元素。
findFirst()
findFirst()用于找到第一次出现的元素
reduce():把Stream 元素组合起来。例如,字符串拼接,数值的 sum,min,max ,average 都是特殊的 reduce。
collect():返回一个新的数据结构,基于Collectors有丰富的处理方法。Collectors类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串,collect()内可以用collectors进行转换:
min():找到最小值。
max():找到最大值。

中间操作:中间操作包括去重、过滤、映射等操作,值得说明的是,如果没有为流定义终端操作,为了避免无谓的计算,中间操作也不会执行

终端操作:终端产生最终的执行结果,并中断流式编程的衔接链,因此结束操作是最后一个操作

.collect(Collectors.toList());//列表
.collect(Collectors.joining(", "));//字符串

.isPresent()
isPresent()可以判断所找到的值是否是null

.orElse()
orElse(null)表示如果一个都没找到返回null

orElse()中可以塞默认值。如果找不到就会返回orElse中你自己设置的默认值。

补充:

Optional<T> findFirst() 
findFirst方法返回Optional包含流中第一个元素的元素,如果findFirst选择的元素为null,它将抛出NullPointerException

所以推荐将findFirst与orElse连用规避空指针的问题,如下所示:

A a = AList.stream().filter(a -> "小明".equals(a.getUserName())) .findFirst().orElse(null);


举例

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class StreamOperation {public static void main(String[] args) {List<StudentVO> list = initList();testFilter(list);}private static List<StudentVO> initList(){List<StudentVO> list = new ArrayList<>();StudentVO student1 = new StudentVO();student1.setKey("a");student1.setValue("str-a");student1.setName("李四");student1.setSex("男");list.add(student1);StudentVO student2 = new StudentVO();student2.setKey("b");student2.setValue("str-b");student1.setName("张三");student1.setSex("女");list.add(student2);StudentVO student3 = new StudentVO();student3.setKey("c");student3.setValue("str-c");student1.setName("小红");student1.setSex("女");list.add(student3);return list;}private static void testFilter(List<StudentVO> list){List<StudentVO> listNew = list.stream().filter(item->item.getKey().equals("a")).collect(Collectors.toList());listNew.forEach(studentVO->{System.out.println(studentVO.getKey());System.out.println(studentVO.getValue());});List<StudentVO> bList = list.stream().filter(item->item.getKey().equals("b")).collect(Collectors.toList());bList.forEach(studentVO->{System.out.println(studentVO.getKey());System.out.println(studentVO.getValue());});}}

1,filter 

2,map

3, sorted排序

private static void testSorted(List<DemoVO> list){//自然排序,先对key进行排序,再对value进行排序。List<DemoVO> collect = list.stream().sorted(Comparator.comparing(DemoVO::getKey).thenComparing(DemoVO::getValue)).collect(Collectors.toList());System.out.println(JSON.toJSONString(collect));collect = list.stream().sorted(Comparator.comparing(DemoVO::getKey).thenComparing(DemoVO::getValue)).collect(Collectors.toList());System.out.println(JSON.toJSONString(collect));
}输出结果:
[{"key":"a","value":"str-a"},{"key":"b","value":"str-b"},{"key":"c","value":"str-c"}]

4,去重

  //去重private static void testDistinct(List<StudentVO> list){List<StudentVO> collect = list.stream().distinct().collect(Collectors.toList());System.out.println(JSON.toJSONString(collect));}//输出结果
[{"key":"a","value":"str-a"},{"key":"b","value":"str-b"},{"key":"c","value":"str-c"}]

5.List<Object>转List<attribute>


private static void convertToList(List<DemoVO> list){List<String> collect = list.stream().map(DemoVO::getValue).collect(Collectors.toList());System.out.println(JSON.toJSONString(collect));
}//输出结果
["str-a","str-b","str-c"]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/576156.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

web.config中httpRunTime的属性

配置httpRuntime也可以让FileUpload上传更大的文件,不过设置太大了会因用户将大量文件传递到该服务器而导致的拒绝服务攻击(属性有说明) <httpRuntime> <httpRuntime useFullyQualifiedRedirectUrl"true|false" maxRequestLength"size in kbytes"…

创建并运用客户化jsp标签

1.在WEB-INF目录下新建message.properties属性文件 文件内容为“key-value”对&#xff0c;添加测试内容如下&#xff1a;titlehello world bodyhello taglib 2.定义初始化类TaglibInit&#xff0c;用…

ArrayList源码阅读

private static void extracted() {ArrayList<StudentVO> arrayList new ArrayList<StudentVO>();arrayList.add(new StudentVO("张三", 23));arrayList.add(new StudentVO("李四", 24));arrayList.add(new StudentVO("王五", 24))…

常用的JS小功能整理

<a href"#" onclick "this.style.behaviorurl(#default#homepage);this.sethomepage(http://www.mingrisoft.com)" style" color:Black; font-size: 9pt; font-family: 宋体; text-decoration :none;" >设置主页</a> <a href&quo…

类的加载过程

类的加载过程 代码 public class Father{private int i test();private static int j method();static{System.out.print("(1)");}Father(){System.out.print("(2)");}{System.out.print("(3)");)public int test(){System.out.print("(…

微软企业库调用Oracle分页存储过程

存储过程&#xff1a;CREATE OR REPLACE PACKAGE pkg_tableTypeIS procedure FY( TableName varchar2, -- 表名getFields varchar2, -- 字段名(全部字段为*) OrderField varchar2, -- 排序字段(必须!支持多字段) whereCondition varchar2, -- 条件语句(不用加where) pageSize i…

Windows服务无法引用.dll的错误

项目中需要使用.NET开发Windows服务来检测MSMQ&#xff0c;但一直无法引用.dll(特别是.dll引用了其它的.dll)&#xff0c;最后google找到了答案&#xff1a; Every window service project, by default targets to .netClient version (which is not full version of .net and …

TC第一次成为room leader

虽然第二题竟然最后没通过system test&#xff0c;用递归的方法超时了 还好challenge 3个&#xff0c;以微弱优势胜过第二名 happy&#xff01; 继续努力转载于:https://www.cnblogs.com/fstang/archive/2012/12/21/2827345.html

[C/C++]BKDRHash

将字符串Hash成整型存储经常用到BKDRHash算法 uint64_t BKDRHash(const char *pszKey) {uint64_t seed 131;register uint64_t uCode0;while(pszKey[0]){uCode uCode *seed (unsigned char)pszKey[0];pszKey;}return uCode; }选择了64位的key&#xff0c;减少冲突的概率。转…

教你如何开发一个 SpringBoot starter

从前从前&#xff0c;有个面试官问我一个 SpringBoot Starter 的开发流程&#xff0c;我说我没有写过 starter&#xff0c;然后就没有然后了&#xff0c;面试官说我技术深度不够。 我想说这东西不是很简单吗&#xff0c;如果要自己写一个出来也是分分钟的事情。至于就因为我没…

nginx 搭建http协议拖动播放 FLV 视频播放服务器

原创作品&#xff0c;允许转载&#xff0c;转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://deidara.blog.51cto.com/400447/235562所需要的 播放器&#xff0c;我用的开源的 JW FLV Media Player我把我的上传到了blog 大家可以下载…

两分钟彻底让你明白Android Activity生命周期(图文)!

转&#xff1a;http://blog.csdn.net/qyf_5445/article/details/8290232 首先看一下Android api中所提供的Activity生命周期图(不明白的&#xff0c;可以看完整篇文章&#xff0c;在回头看一下这个图&#xff0c;你会明白的): Activity其实是继承了ApplicationContext这个类&am…

spring4和spring5的aop执行顺序区别?

spring4单切面 spring4多切面 spring4 spring5

jquery datepicker 点击日期控件不会自动更新input的值

页面代码&#xff1a;<link href"http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel"stylesheet" type"text/css"/> <link href"/static/css/main.css" rel"stylesheet" type"text/css"/…

ArcGIS API for Silverlight中legend控件显示图例问题

转自http://www.gisall.com/html/34/9534-5141.html 在使用ArcGIS API for Silverlight进行地图展示应用的时候&#xff0c;我们都会设置地图图层列表的图例&#xff08;该图例包含有图层名称和图层符号&#xff09;&#xff0c;但是在使用API时却出现了图例无法正常显示&#…

一个b+树库存放多少索引记录

MySQL中InnoDB页的大小默认是16k。也可以自己进行设置。&#xff08;计算机在存储数据的时候&#xff0c;最小存储单元是扇区&#xff0c;一个扇区的大小是 512 字节&#xff0c;而文件系统&#xff08;例如 XFS/EXT4&#xff09;最小单元是块&#xff0c;一个块的大小是 4KB。…

移动发布手机病毒警示信息 发现六种新型病毒

4月17日消息&#xff0c;近期&#xff0c;中国移动监测发现“伪系统杀毒”、“捆绑恶魔”和“伪软件管家”等六款新型手机病毒&#xff0c;造成客户后台自动联网、点播手机游戏类业务、发送垃圾短信并屏蔽10086短信提醒&#xff0c;严重侵害客户权益。 中国移动介绍&#xff0c…

检索函数retrieve

转载于:https://www.cnblogs.com/flowjacky/archive/2012/12/28/2836729.html

Android 安全机制概述

1 Android 安全机制概述 Android 是一个权限分离的系统 。 这是利用 Linux 已有的权限管理机制&#xff0c;通过为每一个 Application 分配不同的 uid 和 gid &#xff0c; 从而使得不同的 Application 之间的私有数据和访问&#xff08; native 以及 java 层通过这种 sandbox …