内容简介

本文主要说明在Java8及以上版本中,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合。

list.stream().mapToDouble(User::getHeight).sum()//和
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值

集合:

List<User> user = new User();
user .stream().collect(Collectors.summingInt(User::getAge))

参数类型:

summarizingDouble 统计数据(double)状态, 其中包括count min max sum和平均值
summarizingInt 统计数据(int)状态, 其中包括count min max sum和平均值
summarizingLong 统计数据(long)状态, 其中包括count min max sum和平均值.

summingInt 求和 返回int类型
summingDouble 求和 返回double类型
summingLong 求和 返回long类型

counting 返回Stream的元素个数

averagingDouble 求平均值 返回double类型
averagingInt 求平均值 返回int类型
averagingLong 求平均值 返回long类型

maxBy 在指定条件下,返回最大值
minBy 在指定条件下,返回最小值

List对象类(StudentInfo)

public class StudentInfo implements Comparable<StudentInfo> {

    //名称
private String name; //性别 true男 false女
private Boolean gender; //年龄
private Integer age; //身高
private Double height; //出生日期
private LocalDate birthday; public StudentInfo(String name, Boolean gender, Integer age, Double height, LocalDate birthday){
this.name = name;
this.gender = gender;
this.age = age;
this.height = height;
this.birthday = birthday;
} public String toString(){
String info = String.format("%s\t\t%s\t\t%s\t\t\t%s\t\t%s",this.name,this.gender.toString(),this.age.toString(),this.height.toString(),birthday.toString());
return info;
} public static void printStudents(List<StudentInfo> studentInfos){
System.out.println("[姓名]\t\t[性别]\t\t[年龄]\t\t[身高]\t\t[生日]");
System.out.println("----------------------------------------------------------");
studentInfos.forEach(s->System.out.println(s.toString()));
System.out.println(" ");
} @Override
public int compareTo(StudentInfo ob) {
return this.age.compareTo(ob.getAge());
//return 1;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Boolean getGender() {
return gender;
} public void setGender(Boolean gender) {
this.gender = gender;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public Double getHeight() {
return height;
} public void setHeight(Double height) {
this.height = height;
} public LocalDate getBirthday() {
return birthday;
} public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
}

测试数据

//测试数据,请不要纠结数据的严谨性
List<StudentInfo> studentList = new ArrayList<>();
studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));

输出Students列表

 //输出List
StudentInfo.printStudents(studentList);

输出结果如下图:

使用filter()过滤List

//查找身高在1.8米及以上的男生
List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());
//输出查找结果
StudentInfo.printStudents(boys);

结果如下图:

List求和(sum)

package com.gp6.list.sum;

import com.gp6.bean.Employee;
import com.gp6.list.utils.ListUtil; import java.math.BigDecimal;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Map;
import java.util.stream.Collectors; /**
* 列表 求和
*
* @author gp6
* @date 2019-07-23
*/
public class TestSum {
public static void main(String[] args) {
List<Employee> employeeList = ListUtil.packEmployeeList(); // 对list中,对年龄求和
Integer ageSum = employeeList.stream().mapToInt(Employee::getAge).sum();
// 121
System.out.println(ageSum); // 对list中,对薪资求和
long salarySum = employeeList.stream().mapToLong(Employee::getSalary).sum();
// 56000
System.out.println(salarySum); // 先将 重量 取出,在计算总和
BigDecimal weightSum = employeeList.stream().map(Employee::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
// 416.45000000000000994759830064140260219573974609375(精度问题)
System.out.println(weightSum); // 根据 性别 分组,再计算出 年龄 信息
Map<Integer, IntSummaryStatistics> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getSex, Collectors.summarizingInt(Employee::getAge)));
// 年龄总和
long ageTmpSum = value.getSum();
// 最大年龄
long ageMax = value.getMax();
// 最小年龄
long ageMin = value.getMin();
// 年龄平均值
double averageAge = value.getAverage(); System.out.println(ageTmpSum);
System.out.println(ageMax);
System.out.println(ageMin);
System.out.println(averageAge);
});
}
}

 

//Map<Integer, LongSummaryStatistics> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getSex, Collectors.summarizingLong(Employee::getAge))); map.forEach((sex, value) -> { 

1.分组
通过groupingBy分组指定字段
list.stream().collect(Collectors.groupingBy(User::getSex));


2.过滤
通过filter方法过滤某些条件
list.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());


3.求和
基本类型:先mapToInt,然后调用sum方法
List.stream().mapToInt(User::getAge).sum();
大数类型:reduce调用BigDecimal::add方法
List.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);


4.最值
最大值
List.stream().map(User::getEntryDate).max(Date::compareTo).get();
最小值
List.stream().map(User::getEntryDate).min(Date::compareTo).get();


5.排序
list.stream().sorted((o1, o2)->o1.getItem().getValue().
compareTo(o2.getItem().getValue())).
collect(Collectors.toList());


sort()
单字段排序,根据id排序 list.sort(Comparator.comparing(Obj::getItem));
多字段排序,根据id,年龄排序 list.sort(Comparator.comparing(Obj::getItem).thenComparing(Obj::getItem));

6.去重
通过distinct方法
List.stream().distinct().collect(Collectors.toList());
对属性
重写方法


7.获取list某个字段组装新list
List.stream().map(a -> a.getId()).collect(Collectors.toList());

												

Java8 使用 stream().filter()过滤List对象等各种操作的更多相关文章

  1. Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

    内容简介 本文主要说明在Java8及以上版本中,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合. List对象类(StudentInfo) public clas ...

  2. Java8 使用 stream().map()提取List对象的某一列值及排重

    List对象类(StudentInfo) public class StudentInfo implements Comparable<StudentInfo> { //名称 privat ...

  3. java8的stream系列教程之filter过滤集合的一些属性

    贴代码 List<Student> lists = new ArrayList<>(); Student student = new Student(); student.se ...

  4. java8 stream ,filter 等功能代替for循环

    直接上代码,比较实在. 对象A public Class A{ private Long id; private String userName; ..... ....省略get和set方法 } 在L ...

  5. java8之stream

    lambda表达式是stream的基础,初学者建议先学习lambda表达式,http://www.cnblogs.com/andywithu/p/7357069.html 1.初识stream 先来一 ...

  6. Java8 使用stream实现各种list操作

    利用java8新特性,可以用简洁高效的代码来实现一些数据处理. 定义1个Apple对象: public class Apple { private Integer id; private String ...

  7. Java8的Stream语法详解(转载)

    1. Stream初体验 我们先来看看Java里面是怎么定义Stream的: A sequence of elements supporting sequential and parallel agg ...

  8. Java8之Stream/Map

    本篇用代码示例结合JDk源码讲了Java8引入的工具接口Stream以及新Map接口提供的常用默认方法.    参考:http://winterbe.com/posts/2014/03/16/java ...

  9. Java8的Stream API使用

    前言 这次想介绍一下Java Stream的API使用,最近在做一个新的项目,然后终于可以从老项目的祖传代码坑里跳出来了.项目用公司自己的框架搭建完成后,我就想着把JDK版本也升级一下吧(之前的项目, ...

  10. Java8之Stream详解

    Java8中提供了Stream对集合操作作出了极大的简化,学习了Stream之后,我们以后不用使用for循环就能对集合作出很好的操作.   一.流的初始化与转换   Java中的Stream的所有操作 ...

随机推荐

  1. LeetCode题集-5 - 最长回文子串之马拉车(二)

    书接上回,我们今天继续来聊聊最长回文子串的马拉车解法. 题目:给你一个字符串 s,找到 s 中最长的回文子串. 01.中心扩展法优化-合并奇偶处理 俗话说没有最好只有更好,看着O(n^2)的时间复杂度 ...

  2. 前端好用API之scrollIntoView

    前情 在前端开发需求中,经常需要用到锚点功能,以往都是获取元素在滚动容器中的位置再设置scrollTop来实现的. scrollIntoView介绍 scrollIntoView()方法将调用它的元素 ...

  3. 【读书笔记】 深入理解JVM第三版 JVM 运行时数据区

    JVM 内存管理 堆 (Heap)线程共享 方法区 (Method Area)线程共享 虚拟机栈(VM Stack) 线程私有 本地方法栈 (Native Method Stack)线程私有 程序计数 ...

  4. AlainConfig

    核心配置对象. 一个配置对象 AlainConfig, 它有一个默认的 一个配置服务:AlainConfigService https://github.com/ng-alain/delon/blob ...

  5. Dapr-4: 交通管制示例应用

    第 4 章 交通管制示例应用 Introduction to the Traffic Control sample application | Microsoft Docs 在前面的章节种,你已经学习 ...

  6. 【MyBatis】学习笔记04:配置文件模板

    [Mybatis]学习笔记01:连接数据库,实现增删改 [Mybatis]学习笔记02:实现简单的查 [MyBatis]学习笔记03:配置文件进一步解读(非常重要) 目录 IDEA配置模板的地方 核心 ...

  7. postgres

    10.67 su - app  docker pull postgres:12.15  docker run -d --name pgsql12 -p 5432:5432 -e "POSTG ...

  8. Qt/C++音视频开发67-保存裸流加入sps/pps信息/支持264/265裸流/转码保存/拉流推流

    一.前言 音视频组件除了支持保存MP4文件外,同时还支持保存裸流即264/265文件,以及解码后最原始的yuv文件.在实际使用过程中,会发现部分视频文件保存的裸流文件,并不能直接用播放器播放,查阅资料 ...

  9. Qt编写百度地图综合应用(在线+离线+区域)

    一.前言 在现在很多的应用系统中,会提供一个地图模块,地图相关的应用和app也是非常多,最广泛的应用就属于导航,地图基本上分在线的和离线的两种,在线的一般都是实时的,数据也是最新的,速度很快路线很准, ...

  10. JavaScript中find()和 filter()方法的区别小结

    前言 JavaScript 在 ES6 上有很多数组方法,每种方法都有独特的用途和好处. 在开发应用程序时,大多使用数组方法来获取特定的值列表并获取单个或多个匹配项. 在列出这两种方法的区别之前,我们 ...