Java8之list.stream的常见使用
本文转自 https://blog.csdn.net/jhgnqq/article/details/123679622 感谢楼主分享
import org.junit.Before;
import org.junit.Test; import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; public class StreamDemo {
List<Student> list = null;
//初始化数据
@Before
public void beforetest() {
list = Arrays.asList(
new Student("Tom", 18, 88, 90),
new Student("Jerry", 20, 77, 89),
new Student("Lily", 17, 98, 79),
new Student("Lucy", 19, 70, 80),
new Student("LiLei", 18, 88, 90),
new Student("HanMeiMei", 21, 87, 79));
} @Test
public void streamtest() {
// filter 过滤器返回还是一个stream流对象
//查询math成绩大于80的学生并遍历输出
list.stream().filter(e->e.getMath()>80).forEach(System.out::println);//.forEach(e->System.out.println(e))
//统计数量count
System.out.println(list.stream().count());
//如统计总分大于160的人数
System.out.println(list.stream().filter(e->e.getEnglish()+e.getMath()>160).count());
//limit 取前n个值
list.stream().limit(3).forEach(System.out::println);
//skip 跳过前n个
list.stream().skip(2).forEach(System.out::println);
//distinct 去除重复数据
list.stream().distinct().forEach(System.out::println);
//map 映射元素可以对元素进行操作 例如对每个学生年龄加1
list.stream().map(e->{
e.setAge(e.getAge()+1);
return e;
}).forEach(System.out::println);
//sorted 排序
//升序
list.stream().sorted((a,b)->{
return a.getEnglish().compareTo(b.getEnglish());
});
//降序
list.stream().sorted((a,b)->{
return b.getEnglish().compareTo(a.getEnglish());
});
//返回第一个元素
Optional<Student> first = list.stream().findFirst();
System.out.println(first.get());
//返回任意一个元素
System.out.println(list.stream().findAny().get());
//anyMatch 是否匹配任意一元素 检查是否包含名字为Tom的
System.out.println(list.stream().anyMatch(e->e.getName().equals("Tom")));
//allMatch 是否匹配所有元素
System.out.println(list.stream().allMatch(e->e.getName().equals("Tom")));
//noneMatch 是否未匹配所有元素
System.out.println(list.stream().noneMatch(e->e.getName().equals("Tom")));
//findFirst 返回元素中第一个值
Student student = list.stream().findFirst().get();
//findAny 返回元素中任意一个值
Student student1 = list.stream().findAny().get();
//max 返回最大值 查询英语成绩最高的学生
Student student2 = list.stream().max((l1,l2)->l2.getEnglish().compareTo(l1.getEnglish())).get();
//min 最小值 将上面l1,l2位置对调
Student student3 = list.stream().max((l1,l2)->l2.getEnglish().compareTo(l1.getEnglish())).get();
//将流对象转为list
list.stream().filter(e->e.getMath()>80).collect(Collectors.toList());
//将流转未set
list.stream().filter(e->e.getMath()>80).collect(Collectors.toSet());
//对对象中的某项进行统计
IntSummaryStatistics c = list.stream().collect(Collectors.summarizingInt(Student::getEnglish));
System.out.println(c);//IntSummaryStatistics{count=6, sum=507, min=79, average=84.500000, max=90}
} } //entity
import lombok.Data;
@data
public class Student {
private String name;
private Integer age;
private Integer math;
private Integer english;
}
另外一篇应用举例 (16条消息) Java8之list.stream的常见使用_大白给小白讲故事的博客-CSDN博客_list stream
public static void main(String[] args) {
List<Student> list = Lists.newArrayList();
list.add(new Student("测试", "男", 18));
list.add(new Student("开发", "男", 20));
list.add(new Student("运维", "女", 19));
list.add(new Student("DBA", "女", 22));
list.add(new Student("运营", "男", 24));
list.add(new Student("产品", "女", 21));
list.add(new Student("经理", "女", 25));
list.add(new Student("产品", "女", 21));
//求性别为男的学生集合
List<Student> l1 = list.stream().filter(student -> student.sex.equals("男")).collect(toList());
//map的key值true为男,false为女的集合
Map<Boolean, List<Student>> map = list.stream().collect(partitioningBy(student -> student.getSex().equals("男")));
//求性别为男的学生总岁数
Integer sum = list.stream().filter(student -> student.sex.equals("男")).mapToInt(Student::getAge).sum();
//按性别进行分组统计人数
Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(Student::getSex, Collectors.summingInt(p -> 1)));
//判断是否有年龄大于25岁的学生
boolean check = list.stream().anyMatch(student -> student.getAge() > 25);
//获取所有学生的姓名集合
List<String> l2 = list.stream().map(Student::getName).collect(toList());
//求所有人的平均年龄
double avg = list.stream().collect(averagingInt(Student::getAge));
//求年龄最大的学生
Student s = list.stream().reduce((student, student2) -> student.getAge() > student2.getAge() ? student:student2).get();
Student stu = list.stream().collect(maxBy(Comparator.comparing(Student::getAge))).get();
//按照年龄从小到大排序
List<Student> l3 = list.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(toList());
//求年龄最小的两个学生
List<Student> l4 = l3.stream().limit(2).collect(toList());
//获取所有的名字,组成一条语句
String str = list.stream().map(Student::getName).collect(Collectors.joining(",", "[", "]"));
//获取年龄的最大值、最小值、平均值、求和等等
IntSummaryStatistics intSummaryStatistics = list.stream().mapToInt(Student::getAge).summaryStatistics();
System.out.println(intSummaryStatistics.getMax());
System.out.println(intSummaryStatistics.getCount());
}
@Data
@AllArgsConstructor
static class Student{
String name;
String sex;
Integer age;
}
Java8之list.stream的常见使用的更多相关文章
- 这可能是史上最好的 Java8 新特性 Stream 流教程
本文翻译自 https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ 作者: @Winterbe 欢迎关注个人微信公众 ...
- 【Java8新特性】面试官:谈谈Java8中的Stream API有哪些终止操作?
写在前面 如果你出去面试,面试官问了你关于Java8 Stream API的一些问题,比如:Java8中创建Stream流有哪几种方式?(可以参见:<[Java8新特性]面试官问我:Java8中 ...
- Java8 如何进行stream reduce,collection操作
Java8 如何进行stream reduce,collection操作 2014-07-16 16:42 佚名 oschina 字号:T | T 在java8 JDK包含许多聚合操作(如平均值,总和 ...
- Java8 方式解决Stream流转其他数组
Java8 方式解决Stream流转其他数组 一. 题记:原来的List转数组用的是如下方式: example private static void listToStringArray(List l ...
- Java8 新特性 Stream 非短路终端操作
非短路终端操作 Java8 新特性 Stream 练习实例 非短路终端操作,就是所有的元素都遍厉完,直到最后才结束.用来收集成自己想要的数据. 方法有: 遍厉 forEach 归约 reduce 最大 ...
- Java8 新特性 Stream 短路终端操作
短路终端操作 Java8 新特性 Stream 练习实例 传入一个谓词,返回传为boolean,如果符合条件,则直接结束流. 匹配所有 allMatch 任意匹配 anymMatch 不匹配 none ...
- Java8 新特性 Stream 无状态中间操作
无状态中间操作 Java8 新特性 Stream 练习实例 中间无状态操作,可以在单个对单个的数据进行处理.比如:filter(过滤)一个元素的时候,也可以判断,比如map(映射)... 过滤 fil ...
- Java8 新特性 Stream() API
新特性里面为什么要加入流Steam() 集合是Java中使用最多的API,几乎每一个Java程序都会制造和处理集合.集合对于很多程序都是必须的,但是如果一个集合进行,分组,排序,筛选,过滤...这些操 ...
- java8学习之Stream分组与分区详解
Stream应用: 继续举例来操练Stream,对于下面这两个集合: 需求是:将这两个集合组合起来,形成对各自人员打招呼的结果,输出的结果如: "Hi zhangsan".&quo ...
- 【Java8新特性】面试官问我:Java8中创建Stream流有哪几种方式?
写在前面 先说点题外话:不少读者工作几年后,仍然在使用Java7之前版本的方法,对于Java8版本的新特性,甚至是Java7的新特性几乎没有接触过.真心想对这些读者说:你真的需要了解下Java8甚至以 ...
随机推荐
- MQTT应用:Air780EP低功耗4G模组AT开发
终于要讲一讲MQTT应用! 本文应各位大佬邀请,详细讲解Air780EP模组MQTT应用的多个AT命令. Air780EP是低功耗4G模组之一,支持全系列的AT指令以及LuatOS脚本二次开发. ...
- 一文带你搞懂GaussDB数据库性能调优
本文分享自华为云社区<[GaussTech技术专栏]GaussDB性能调优>,作者:GaussDB 数据库. 数据库性能调优是一项复杂且系统性的工作,需要综合考虑多方面的因素.因此,调优人 ...
- Windows 杜比OEM授权
我们中高端的windows笔记本上都可以看到Dolby音效,TV电视上也有支持Dolby显示选项. 杜比主要有几类:Dolby全景声(也叫Atmos).Dolby视界(Vision).杜比影院(Dol ...
- python get请求传array数组
前言 使用传统的http发get请求时,如果传参为array数组,参数名称为a时,可以这样传值a=1&a=2&a=3,但是当只有一个时,这种方式就不合理了. get请求还有另外一种方式 ...
- golang 判断文件或文件夹是否存在
//判断文件是否存在 存在返回 true 不存在返回false func checkFileIsExist(filename string) bool { var exist = true if _, ...
- mongodb之进阶
常用命令: 1.查看数据库空间大小 db.stats(); 默认是bytes单位 { "db" : "xxx", //当前数据库 "collectio ...
- The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online (The 2nd Universal Cup
The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online (The 2nd Universal Cup. Stage 1: Qingdao) J ...
- 探索 TypeScript 编程的利器:ts-morph 入门与实践
我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品.我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值. 本文作者:贝儿 背景 在开发 web IDE 中生成代码大纲的功能时 ...
- Asp.net MVC中的Http管道事件为什么要以Application_开头?
今天遇到一个问题,需要在API请求结束时,释放数据库链接,避免连接池被爆掉. 按照以往的经验,需要实现IHttpModule,具体不展开了. 但是实现了IHttpModule后,还得去web.conf ...
- ZCMU-1120
就这样 #include<cmath> #include<cstdio> #include<iostream> using namespace std; int m ...