Java8新特性 Stream

 

  • 首先创建一个用户的实体类,包括姓名、年龄、性别、地址、赏金 几个属性 
@Data
public class User {//姓名private String name;//年龄private Integer age;//性别private Integer sex;//地址private String address;//赏金private BigDecimal money;public User(String name, Integer age, Integer sex, String address,BigDecimal money) {this.name = name;this.age = age;this.sex = sex;this.address = address;this.money = money;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", age=" + age +", sex=" + sex +", money=" + money +", address='" + address + '\'' +'}';}
}
  • 我们在创建一个测试类,包含主方法,并创建一个数据源,作为我们测试的对象
public class Stream {public static void main(String[] args) {}public static List<User> users(){List<User> list = Arrays.asList(new User("赵", 18, 0, "安徽",new BigDecimal(1000)),new User("钱", 16, 1, "江苏",new BigDecimal(500)),new User("孙", 17, 1, "山东",new BigDecimal(800)),new User("李", 99, 0, "河南",new BigDecimal(100000)),new User("周", 19, 0, "陕西",new BigDecimal(900)),new User("武", 45, 0, "上海",new BigDecimal(600)),new User("郑", 48, 0, "北京",new BigDecimal(1100)),new User("王", 18, 1, "广西",new BigDecimal(800)));return list;}
}
  • stream使用
  • filter
  • distinct
  • sorted
  • limit
  • skip
  • map
  • flatMap
  • allMatch
  • anyMatch
  • noneMatch
  • findFirst
  • findAny
  • count
  • max
  • min
  • avg
  • sum
  • join
  • group
  • partition
	/*filter过滤(T-> boolean)*/public static void filter(){List<User> list = users();List<User> newlist = list.stream().filter(user -> user.getAge() > 20).collect(Collectors.toList());for (User user : newlist) {System.out.println(user.getName()+" --> "+ user.getAge());}}/*distinct 去重*/数据源中复制new User("赵", 18, 0, "安徽",new BigDecimal(1000)) 并粘贴两个public static void distinct(){List<User> list = users();List<User> newlist = list.stream().distinct().collect(Collectors.toList());for (User user : newlist) {System.out.println(user.getName()+" --> "+ user.getAge());}}/*sorted排序*/public static void sorted(){List<User> list = users();List<User> newlist = list.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());for (User user : newlist) {System.out.println(user.getName()+" --> "+ user.getAge());}}/*limit返回前n个元素*/public static void limit(){List<User> list = users();List<User> newlist = list.stream().sorted(Comparator.comparingInt(User::getAge)).limit(2).collect(Collectors.toList());for (User user : newlist) {System.out.println(user.getName()+" --> "+ user.getAge());}}/*skip去除前n个元素*/public static void skip(){List<User> list = users();List<User> newlist = list.stream().sorted(Comparator.comparingInt(User::getAge)).skip(2).collect(Collectors.toList());for (User user : newlist) {System.out.println(user.getName()+" --> "+ user.getAge());}}/*map(T->R)*/public static void map(){List<User> list = users();List<String> newlist = list.stream().map(User::getName).distinct().collect(Collectors.toList());for (String add : newlist) {System.out.println(add);}}/*flatMap(T -> Stream<R>)*/public static void flatmap(){List<String> flatmap = new ArrayList<>();flatmap.add("赵,钱");flatmap.add("孙,李,周");/*这里原集合中的数据由逗号分割,使用split进行拆分后,得到的是Stream<String[]>,字符串数组组成的流,要使用flatMap的Arrays::stream将Stream<String[]>转为Stream<String>,然后把流相连接*/flatmap = flatmap.stream().map(s -> s.split(",")).flatMap(Arrays::stream).collect(Collectors.toList());for (String name : flatmap) {System.out.println(name);}}---结果---赵钱孙李周/*allMatch(T->boolean)检测是否全部满足参数行为*/public static void allMatch(){List<User> list = users();boolean flag = list.stream().allMatch(user -> user.getAge() >= 17);System.out.println(flag);}---结果---false/*anyMatch(T->boolean)检测是否有任意元素满足给定的条件*/public static void anyMatch(){List<User> list = users();boolean flag = list.stream().anyMatch(user -> user.getSex() == 1);System.out.println(flag);}---结果---true/*noneMatchT->boolean)流中是否有元素匹配给定的 T -> boolean条件*/public static void noneMatch(){List<User> list = users();boolean flag = list.stream().noneMatch(user -> user.getAddress().contains("郑州"));System.out.println(flag);}---结果---true/*findFirst( ):找到第一个元素*/public static void findfirst(){List<User> list = users();Optional<User> optionalUser = list.stream().sorted(Comparator.comparingInt(User::getAge)).findFirst();System.out.println(optionalUser.toString());}---结果---Optional[User{name='赵', age=16, sex=1, money=500, address='安徽'}]/*findAny( ):找到任意一个元素*/public static void findAny(){List<User> list = users();
//        Optional<User> optionalUser = list.stream().findAny();Optional<User> optionalUser = list.stream().findAny();System.out.println(optionalUser.toString());}---结果---Optional[User{name='钱', age=18, sex=0, money=1000, address='江苏'}]/*计算总数*/public static void count(){List<User> list = users();long count = list.stream().count();System.out.println(count);}---结果---8/*最大值最小值*/public static void max_min(){List<User> list = users();Optional<User> max = list.stream().collect(Collectors.maxBy(Comparator.comparing(User::getAge)));Optional<User> min = list.stream().collect(Collectors.minBy(Comparator.comparing(User::getAge)));System.out.println("max--> " + max+"  min--> "+ min);}---结果---max--> Optional[User{name='李', age=99, sex=0, money=100000, address='山东'}]          min--> Optional[User{name='钱', age=16, sex=1, money=500, address='江苏'}]/*求和_平均值*/public static void sum_avg(){List<User>list = users();int totalAge = list.stream().collect(Collectors.summingInt(User::getAge));System.out.println("totalAge--> "+ totalAge);/*获得列表对象金额, 使用reduce聚合函数,实现累加器*/BigDecimal totalMpney = list.stream().map(User::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);System.out.println("totalMpney--> " + totalMpney);double avgAge = list.stream().collect(Collectors.averagingInt(User::getAge));System.out.println("avgAge--> " + avgAge);}---结果---totalAge--> 280totalMpney--> 105700avgAge--> 35.0/*一次性得到元素的个数、总和、最大值、最小值*/public static void allVlaue(){List<User> list = users();IntSummaryStatistics statistics = list.stream().collect(Collectors.summarizingInt(User::getAge));System.out.println(statistics);}---结果---IntSummaryStatistics{count=8, sum=280, min=16, average=35.000000, max=99}/*拼接*/public static void join(){List<User> list = users();String names = list.stream().map(User::getName).collect(Collectors.joining(", "));System.out.println(names);}---结果---赵, 钱, 孙, 李, 周, 武, 郑, 王/*分组*/public static void group(){Map<Integer, List<User>> map = users().stream().collect(Collectors.groupingBy(User::getSex));System.out.println(new Gson().toJson(map));System.out.println();Map<Integer, Map<Integer,List<User>>> map2 = users().stream().collect(Collectors.groupingBy(User::getSex,Collectors.groupingBy(User::getAge)));System.out.println(new Gson().toJson(map2));}---结果---
{
"0":[
{"name":"赵","age":18,"sex":0,"address":"安徽","money":1000},
{"name":"钱","age":99,"sex":0,"address":"山东","money":100000},
{"name":"孙","age":19,"sex":0,"address":"河南","money":900},
{"name":"李","age":45,"sex":0,"address":"江苏","money":600},
{"name":"周","age":48,"sex":0,"address":"陕西","money":1100}
],
"1":[
{"name":"武","age":16,"sex":1,"address":"上海","money":500},
{"name":"郑","age":17,"sex":1,"address":"北京","money":800},
{"name":"王","age":18,"sex":1,"address":"深圳","money":800}
]
}{"0":
{"48":[{"name":"赵","age":48,"sex":0,"address":"安徽","money":1100}],
"18":[{"name":"钱","age":18,"sex":0,"address":"山东","money":1000}],
"19":[{"name":"孙","age":19,"sex":0,"address":"河南","money":900}],
"99":[{"name":"李","age":99,"sex":0,"address":"江苏","money":100000}],
"45":[{"name":"周","age":45,"sex":0,"address":"陕西","money":600}]},
"1":
{"16":[{"name":"武","age":16,"sex":1,"address":"上海","money":500}]
,"17":[{"name":"郑","age":17,"sex":1,"address":"北京","money":800}],
"18":[{"name":"王","age":18,"sex":1,"address":"深圳","money":800}]}}/*分组合计*/public static void groupCount(){Map<Integer, Long> num = users().stream().collect(Collectors.groupingBy(User::getSex, Collectors.counting()));System.out.println(num);Map<Integer, Long> num2 = users().stream().filter(user -> user.getAge()>=18).collect(Collectors.groupingBy(User::getSex, Collectors.counting()));System.out.println(num2);}---结果---{0=5, 1=3}{0=5, 1=1}/*分区*/public static void partitioningBy(){List<User> list = users();Map<Boolean, List<User>> part = list.stream().collect(Collectors.partitioningBy(user -> user.getAge() <= 30));System.out.println(new Gson().toJson(part));}---结果---
{"false":
[
{"name":"赵","age":99,"sex":0,"address":"江苏","money":100000},
{"name":"钱","age":45,"sex":0,"address":"山东","money":600},
{"name":"孙","age":48,"sex":0,"address":"河南","money":1100}],
"true":
[
{"name":"李","age":18,"sex":0,"address":"陕西","money":1000},
{"name":"周","age":16,"sex":1,"address":"安徽","money":500},
{"name":"武","age":17,"sex":1,"address":"上海","money":800},
{"name":"郑","age":19,"sex":0,"address":"北京","money":900},
{"name":"王","age":18,"sex":1,"address":"深圳","money":800}]
}
  • for
  • filter
  • map
  • toList
  • toMap
  • distinct
  • sorted
  • group

package stream;import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;public class StreamApplication {static class User {private Integer id;private String name;public User(Integer id, String name) {this.id = id;this.name = name;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +'}';}}public static void main(String[] args) {List<User> userList = Arrays.asList(new User(1, "a"),new User(2, "b"),new User(3, "c"),new User(4, "d"));// for 循环userList.forEach(user -> System.out.println(user.getId()));// map键拼接Map<String,String> map = new HashMap();userList.stream().forEach(user -> map.put(user.getId() +"_"+user.getName(),user.getName() ););// filter// 数字比较List<User> userList = userList.stream().filter(user -> user.getId() > 2).collect(Collectors.toList());// 字符串List<User> userList = userList.stream().filter(user -> "a".equals(user.getName())).collect(Collectors.toList());// List<String> nameList<User> userList = userList.stream().filter(user -> user.getId() > 2).map(User::getName).collect(Collectors.toList());// countlong count  = userList.stream().filter(user -> user.getId() > 2).count()// map 用法List<Integer> users = userList.stream().map(User::getId).collect(Collectors.toList()); // toList用法List<Integer> list = userList.stream().map(User::getId).collect(Collectors.toList());// toMap 用法Map<Integer, String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName)); // 使用distinct()方法去重List<Student> list = new ArrayList<>();List<Student> distinctList = list.stream().distinct().collect(Collectors.toList());// sorted()方法对元素进行排序List<Student> list = new ArrayList<>(); // 按照分数升序排序List<Student> sortedList = list.stream()                           				 .sorted(Comparator.comparingDouble(Student::getScore)).collect(Collectors.toList());// 按照年龄降序排序List<Student> reversedList = list.stream()                               .sorted(Comparator.comparingInt(Student::getAge).reversed()).collect(Collectors.toList());// groupingBy()方法对元素进行分组List<Student> list = new ArrayList<>(); Map<String, List<Student>> groupByMajor = list.stream()                                              			                                .collect(Collectors.groupingBy(Student::getMajor));}
}

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

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

相关文章

【解决Typora图片不是显示问题】PicGo+Github+Typora+ onedrive/坚果云 实现笔记同步

【解决Typora图片不是显示问题】PicGo、Github、Typora实现笔记同步 写在前面&#xff1a; typora笔记软件使用记录typora图片上传问题&#xff1a;原因分析&#xff1a;解决方案&#xff1a;PicGoGithubTypora 坚果云/onedrive 实现笔记同步第一步. 设置上传模式&#xff1a;u…

华为安防监控摄像头

华为政企42 华为政企 目录 上一篇华为政企城市一张网研究报告下一篇华为全屋wifi6蜂鸟套装标准

Hypervisor Display架构

Hypervisor Display架构部分 1&#xff0c;所有LA侧的APP与显示相关的调用最终都会交由SurfaceFlinger处理 2&#xff0c;SurfaceFlinger会最终调用android.hardware.graphics.composer2.4-service服务 3&#xff0c;android.hardware.graphics.composer2.4-service服务会调用G…

一、神经元与激活函数

神经网络是一种大规模的并行分布式处理器&#xff0c;天然具有存储并使用经验知识的能力。它从两个方面上模拟大脑:(1)网络获取的知识是通过学习来获取的;(2)内部神经元的连接强度&#xff0c;即突触权重&#xff0c;用于储存获取的知识。—— Haykin [1994] 生物学家在20世纪初…

CSS之em、px、rem的区别

前端 作为一个前端开发工程师&#xff0c;关于这些长度单位还是得了解一下。虽然在日常的开发中px、%用的多些&#xff0c;也会用到vh、vw&#xff0c;其他的虽然用的少但也得了解&#xff0c;说不定就能解决你样式中的问题呢。 计量单位 在css中计量单位分相对长度单位和绝…

XILINX-Zynq UltraScale+MPSoc 开发笔记

1. 资料信息 2. IDE集成开发环境 3. petalinux开发 3.1 环境搭建 1. 创建一个ubuntu18.04&#xff08;或者其他版本&#xff09;&#xff0c;根据UG1144文档安装ubuntu下对petalinux的依懒工具。 2. 下载petalinux对应版本&#xff0c;链接&#xff1a;Downloads (xilinx.co…

【mysql】出错 Subquery returns more than 1 row

问题 查找出一下子查询返回超过1行 SELECT cc.id,DATE_FORMAT(cc.CREATE_TIME,%Y%m%d) as day_id, IFNULL((select f.source FROM strong_contact_fea f where f.id cc.id and STR_SPEC_IDS2023091145),10501) as strong_prod_level_1, IFNULL((select f.source from stron…

Python---端口和端口号的介绍

1. 问题思考 不同电脑上的飞秋之间进行数据通信&#xff0c;它是如何保证把数据给飞秋而不是给其它软件呢? 其实&#xff0c;每运行一个网络程序都会有一个端口&#xff0c;想要给对应的程序发送数据&#xff0c;找到对应的端口即可。 端口效果图: 2. 什么是端口 端口是传…

iOS将framework转为xcframework

拆分framework 先把framework拷贝到两个文件夹下边&#xff0c;这里只需要armv7、arm64、x86_64。 mkdir iphoneos iphonesimulator cp -R mysdk.framework iphoneos cp -R mysdk.framework iphonesimulator 把iphoneos中的模拟器指令集删除&#xff0c;只保留armv7和arm64 …

电巢助力第十届图像技术高峰论坛圆满落幕,回顾西电与电巢的校企合作四年硕果累累

图像技术高峰论坛圆满落幕 12月17日&#xff0c;由中国图象图形学学会、陕西省科学技术协会主办、西安电子科技大学通信工程学院、陕西省创新驱动共同体承办的“第十届图像技术高峰论坛暨陕西第五届图像处理与分析研讨会”在陕西西安成功举办。电巢科技作为本次论坛的承办单位&…

某电子文档安全管理系统 SQL注入漏洞复现

漏洞介绍 亿赛通电子文档安全管理系统 (简称: CDG)是一款电子文档安全加密软件&#xff0c;该系统利用驱动层透明加密技术&#xff0c;通过对电子文档的加密保护&#xff0c;防止内部员工泄密和外部人员非法窃取企业核心重要数据资产&#xff0c;对电子文档进行全生命周期防护…

RHCE8 资料整理(十二)

RHCE8 资料整理 第 33 章 jinja2模板的使用31.1 if 判断33.2 for循环33.3 handlers 第 33 章 jinja2模板的使用 详细参考 https://blog.csdn.net/u010230019/article/details/128561872 https://blog.csdn.net/u010230019/article/details/128477679 假设目前Nginx的配置文件在…

未来仓储新玩法小空间做大文章

身处智能消费时代的大家都应该有深刻感受&#xff0c;物流速度在逐年增快。根据国家邮政局预估&#xff0c;2020 年快递业务吞吐量超 740 亿件&#xff0c;同比增长 18%。 面对日益增加的商品交付量&#xff0c;不得不重新定义产品分销方式&#xff0c;从而满足当今互联网消费…

从零开始学HBase:打造你的大数据技能库!

介绍&#xff1a;HBase是一个分布式的、面向列的开源数据库&#xff0c;源于Fay Chang所撰写的Google论文“Bigtable&#xff1a;一个结构化数据的分布式存储系统”。类似于Bigtable利用了Google文件系统&#xff08;File System&#xff09;提供的分布式数据存储&#xff0c;H…

<八>JavaScript中的对象及对像的增删改查

使用基本数据变量所创建的变量都是独立的&#xff0c;不能成为一个整体&#xff0c;对象属于复合型的数据类型&#xff0c;在对象中可以保存多个不同的数据类型的属性。 一、对象的分类 1.1内建对象 由ES标准中定义的对象 比如&#xff1a;Match、String、Number、Boolean、…

【Qt】Qt Creator 警告: Unused parameter ‘xxx‘

1. 问题 Qt开发中&#xff0c;有些函数参数没有使用&#xff0c;会报Unused parameter xxx警告&#xff0c;这个警告不影响代码正常运行。 2. 屏蔽这个警告的方法 2.1 方法1 函数中添加 Q_UNUSED(arg); TestClass::TestClass(QObject *parent) {Q_UNUSED(parent); }2.2 方…

【AI-2】深度学习框架详解

目前&#xff0c;有许多流行的深度学习框架可供选择&#xff0c;下面列举一些常见的深度学习框架&#xff1a; TensorFlow&#xff08;Google&#xff09; TensorFlow&#xff1a;由Google开发的开源深度学习框架&#xff0c;提供了丰富的工具和库&#xff0c;支持各种深度学…

IP查询类API接口查询,含各精度IP归属地查询接口

IP查询 IP归属地-IPv4高精版&#xff1a;根据IP地址查询归属地信息&#xff0c;支持到中国地区&#xff08;不含港台地区&#xff09;街道级别&#xff0c;包含国家、省、市、区县、详细地址和运营商等信息。IP归属地-IPv4区县级&#xff1a;根据IP地址查询归属地信息&#xf…

华为atlas300安装教程

1、安装包位置&#xff1a; /data/ai_install_packages 2、添加HwHiAiUser用户&#xff1a; groupadd -g 1000 HwHiAiUser useradd -g HwHiAiUser -u 1000 -d /home/HwHiAiUser -m HwHiAiUser -s /bin/bash 3、安装驱动&#xff1a; ./Ascend-hdk-310p-npu-driver_6.0.0_l…

前端FLV视频直播解决方案

项目背景&#xff1a; 1. 后台给出一个地址&#xff0c;持续不断的推送flv视频流。 2.前端需要接收视频流&#xff0c;并寻找合适的播放插件。 一开始&#xff1a; 其实用的是xgplayer&#xff08;西瓜视频&#xff09;。 官网地址&#xff1a;西瓜播放器 使用的是直播&a…