Java8 快速实现List转map 、分组、过滤等操作

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达


关注公众号后台回复pay或mall获取实战项目资料+视频

作者:IT小白_L

https://blog.csdn.net/lu930124/article/details/77595585

利用java8新特性,可以用简洁高效的代码来实现一些数据处理。

定义1个Apple对象:

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }
}

添加一些测试数据:

List<Apple> appleList = new ArrayList<>();//存放apple对象集合
 
Apple apple1 =  new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple apple2 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple3 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);
 
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);

1、分组

List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:

//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
 
System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

2、List转Map

id为key,apple对象为value,可以这么做:

/**
 * List -> Map
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key ....
 *  apple1,apple12的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

打印appleMap

{1=Apple{id=1, name='苹果1', money=3.25, num=10}, 2=Apple{id=2, name='香蕉', money=2.89, num=30}, 3=Apple{id=3, name='荔枝', money=9.99, num=40}}

3、过滤Filter

从集合中过滤出来符合条件的元素:

//过滤出符合条件的数据
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
 
System.err.println("filterList:"+filterList);
[Apple{id=2, name='香蕉', money=2.89, num=30}]

4、求和

将集合中的数据按照某个属性求和:

//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48

5、查找流中最大 最小值

Collectors.maxBy 和 Collectors.minBy 来计算流中的最大或最小值。搜索Java知音公众号,回复“后端面试”,送你一份Java面试题宝典

Optional<Dish> maxDish = Dish.menu.stream().
      collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
 
Optional<Dish> minDish = Dish.menu.stream().
      collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);

6、去重

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
 
// 根据id去重
     List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );

下表展示 Collectors 类的静态工厂方法。

工厂方法返回类型作用
toListList<T>把流中所有项目收集到一个 List
toSetSet<T>把流中所有项目收集到一个 Set,删除重复项
toCollectionCollection<T>把流中所有项目收集到给定的供应源创建的集合menuStream.collect(toCollection(), ArrayList::new)
countingLong计算流中元素的个数
sumIntInteger对流中项目的一个整数属性求和
averagingIntDouble计算流中项目 Integer 属性的平均值
summarizingIntIntSummaryStatistics收集关于流中项目 Integer 属性的统计值,例如最大、最小、 总和与平均值
joiningString连接对流中每个项目调用 toString 方法所生成的字符串collect(joining(", "))
maxByOptional<T>一个包裹了流中按照给定比较器选出的最大元素的 Optional, 或如果流为空则为 Optional.empty()
minByOptional<T>一个包裹了流中按照给定比较器选出的最小元素的 Optional, 或如果流为空则为 Optional.empty()
reducing归约操作产生的类型从一个作为累加器的初始值开始,利用 BinaryOperator 与流 中的元素逐个结合,从而将流归约为单个值累加int totalCalories = menuStream.collect(reducing(0, Dish::getCalories, Integer::sum));
collectingAndThen转换函数返回的类型包裹另一个收集器,对其结果应用转换函数int howManyDishes = menuStream.collect(collectingAndThen(toList(), List::size))
groupingByMap<K, List<T>>根据项目的一个属性的值对流中的项目作问组,并将属性值作 为结果 Map 的键
partitioningByMap<Boolean,List<T>>根据对流中每个项目应用谓词的结果来对项目进行分区

有热门推荐????

2020年11月程序员工资统计,平均14327元

Mybatis插件扩展以及与Spring整合原理

用了 10 年 Windows 后,我最终转向 Linux
Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合
Redis为什么又引入了多线程?单线程不香了?

Spring Security 真正的前后分离实现

自定义实现拦截器mybatis插件,让你为所欲为!

最后分享一套微服务电商项目教程(资料笔记+视频):点击阅读全文获取面试资料+项目实战资料(电商/聚合支付)

SPringCloud微服电商完整务教程

1.框架搭建
- 电商项目介绍
- 微服务环境搭建
- 数据库搭建

2.分布式存储系统
- FastDFS原理讲解
- 文件上传
- 文件下载
3.商品发布
- 表结构梳理
- 代码生成器的使用
- 商品增删改
- 商品查询
4.lua,canal实现广告缓存
- 首页广告表设计
- Lua安装使用讲解
- Nginx限流实战
- Canal安装,原理介绍
- Canal同步数据实现
5.索引搜索
- ES安装讲解
- Kibana安装讲解
- DSL语句
- ES API使用
6.商品搜索
- ES 高级搜索功能
- ES 排序规则

 7.Thymeleaf实现静态页面
- Thymeleat 缓存配置讲解
- 搜索页面讲解
8.微服务网关和Jwt令牌
- 微服务网关Zuul/Gateway介绍
- 网关之负载和限流
- 用户服务搭建
- JWT token讲解
- 网关鉴权
9.Spring Security Oauth2
- 单点登陆介绍
- Oauth2介绍
- 共钥私钥讲解
- 加密算法讲解
10.购物车
- 购物车分析和购物车种类分析
- 订单服务创建
- 购物车功能实现
11.订单
- 用户地址测试
- 下单问题分析,幂等
- 用户积分规则
- 二维码生产讲解
- 微信支付流程及模式讲解
12.微信支付
- 微信支付SDK使用讲解
- 微信支付状态查询
- 内网穿透 花生壳
- 微信支付回调
- rabbitMQ 延时队列讲解
13.秒杀基础
- 秒杀需求分析
- 秒杀服务搭建
- 秒杀之Redis
- 秒杀之多线程
14.秒杀核心
- 重复抢单下单问题
- 超卖问题
- 秒杀支付
15.分布式事物
- 分布式事物介绍
- CAP理论介绍
- 2pc/3pc 机制讲解
- TCC事物补偿
- Seata案列讲解
16.高可用集群
- 分布式和集群概念
- Eureka集群介绍
- Redis 集群介绍
- RabbitMq集群安装

点击阅读原文,前往上面微服务电商教程文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值