【java8 stream操作List集合】

内容简介

本文主要说明在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)

测试数据

//测试数据,请不要纠结数据的严谨性
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());

转载:https://www.cnblogs.com/yelanggu/p/13431511.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值