常用stream方法记录

news2024/10/5 17:17:46

目录

  • 过滤filter()
  • 获取最大最小值
  • 根据条件统计数量
  • list转map
    • key值唯一
    • key值不唯一
  • distinct去重
  • groupingBy分组
  • map遍历
  • 取list中某元素组成新的list
  • list转数组
    • String
    • 基本数据类型数组转换
  • 数组转list
    • Arrays.asList()
    • Collections.addAll
    • 基本数据类型数组转list
  • 源码和执行结果参考
    • 执行源码
    • 执行结果

过滤filter()

List<DemoEntity> filterList = initDatas.stream().filter(demo -> (StringUtils.isNotEmpty(demo.getBrief()))).collect(Collectors.toList());
// 循环
filterList.forEach(demo->System.out.println(demo.toString()));

获取最大最小值

List<DemoEntity> filterAgeList = initDatas.stream().filter(demo -> demo.getAge() != null).collect(Collectors.toList());
Integer maxAge = filterAgeList.stream().max(Comparator.comparing(DemoEntity::getAge)).get().getAge();
Integer minAge = filterAgeList.stream().min(Comparator.comparing(DemoEntity::getAge)).get().getAge();

根据条件统计数量

long count = initDatas.stream().distinct().filter(DemoEntity -> DemoEntity.getAge() != null &&  DemoEntity.getAge() > 30).count();
System.out.println("去重后统计大于30岁的人数="+count);

list转map

key值唯一

Map<Integer, DemoEntity> initMap = initDatas.stream().collect(Collectors.toMap(DemoEntity::getId, demo -> demo));

key值不唯一

  • key值冲突会报错,可以设置重复覆盖操作, 后面数据覆盖前面的指定key2,指定key1则前面的覆盖后续重复的key的值
Exception in thread "main" java.lang.IllegalStateException: Duplicate key DemoEntity(id=6, name=Monica, sex=F, age=59, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1254)
	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
	at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1380)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at com.renxiaozhao.service.demo.stream.StreamUtilDemo.main(StreamUtilDemo.java:32)
Map<Integer, DemoEntity> initMap = initDatas.stream().collect(Collectors.toMap(DemoEntity::getId, Function.identity(), (key1, key2) -> key2));

distinct去重

List<DemoEntity> distincts = initDatas.stream().distinct().collect(Collectors.toList());

groupingBy分组

Map<Integer, List<DemoEntity>> groupMap = distincts.stream().collect(Collectors.groupingBy(demo -> demo.getId()));

map遍历

groupMap.forEach((key, value) -> {
    System.out.println("key = " + key + ", value = " + value);
});

取list中某元素组成新的list

List<String> names = initDatas.stream().map(DemoEntity::getName).collect(Collectors.toList());
List<Integer> ids = initDatas.stream().map(DemoEntity::getId).collect(Collectors.toList());

list转数组

String

String[] arr = names.toArray(new String[names.size()]);

基本数据类型数组转换

int[] intArr = ids.stream().mapToInt(Integer::intValue).toArray();

数组转list

Arrays.asList()

String[] arr = {"aa","bb","cc"};
List<String> list = Arrays.asList(arr);

list不能增删改操作

Collections.addAll

String[] arr = {"aa","bb","cc"};
List<String> list1= new ArrayList<>();
Collections.addAll(list1, arr);

list可以增删改操作

基本数据类型数组转list

int[] intArr= {1,2,3};
List<Integer> intList = Arrays.stream(intArr).mapToObj(Integer::new).collect(Collectors.toList());

源码和执行结果参考

执行源码

package com.renxiaozhao.service.demo.stream;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

public class StreamUtilDemo {

    public static void main(String[] args) throws ParseException {
        //初始化数据
        List<DemoEntity> initDatas = initData();
        //获取去除简介brief为空的数据后的list
        List<DemoEntity> filterList = initDatas.stream().filter(demo -> (StringUtils.isNotEmpty(demo.getBrief()))).collect(Collectors.toList());
        System.out.println("过滤brief为空后的数据-----------------------------------");
        filterList.forEach(demo->System.out.println(demo.toString()));
        //获取最成熟的年龄,先过滤年龄为空的数据
        List<DemoEntity> filterAgeList = initDatas.stream().filter(demo -> demo.getAge() != null).collect(Collectors.toList());
        Integer maxAge = filterAgeList.stream().max(Comparator.comparing(DemoEntity::getAge)).get().getAge();
        Integer minAge = filterAgeList.stream().min(Comparator.comparing(DemoEntity::getAge)).get().getAge();
        System.out.println("最大年龄="+maxAge+",最小年龄="+minAge);
        //获取去重后大于30岁的人数
        long count = initDatas.stream().distinct().filter(DemoEntity -> DemoEntity.getAge() != null &&  DemoEntity.getAge() > 30).count();
        System.out.println("去重后统计大于30岁的人数="+count);
        //list转map key值冲突会报错,可以设置重复覆盖操作
        //Map<Integer, DemoEntity> initMap = initDatas.stream().collect(Collectors.toMap(DemoEntity::getId, demo -> demo));
        //后面数据覆盖前面的指定key2,指定key1则前面的覆盖后续重复的key的值
        System.out.println("list转map key冲突时覆盖前面的key值设置,详细数据如下:");
        Map<Integer, DemoEntity> initMap = initDatas.stream().collect(Collectors.toMap(DemoEntity::getId, Function.identity(), (key1, key2) -> key2));
        initMap.forEach((key, value) -> {
            System.out.println("key = " + key + ", value = " + value);
        });
        //分组
        System.out.println("distinct去重");
        List<DemoEntity> distincts = initDatas.stream().distinct().collect(Collectors.toList());
        System.out.println("list转Map,按照id分组");
        Map<Integer, List<DemoEntity>> groupMap = distincts.stream().collect(Collectors.groupingBy(demo -> demo.getId()));
        groupMap.forEach((key, value) -> {
            System.out.println("key = " + key + ", value = " + value);
        });
        //取list中name组成新的list
        List<String> names = initDatas.stream().map(DemoEntity::getName).collect(Collectors.toList());
        List<Integer> ids = initDatas.stream().map(DemoEntity::getId).collect(Collectors.toList());
        System.out.println("新list:"+names.toString());
        System.out.println("新list去重:"+names.stream().distinct().collect(Collectors.toList()).toString());
        //list转数组
        String[] arr = names.toArray(new String[names.size()]);
        System.out.println("list.toarray转数组"+Arrays.toString(arr));
        int[] intArr = ids.stream().mapToInt(Integer::intValue).toArray();
        System.out.println("list通过stream转数组"+Arrays.toString(intArr));
        //数组转list
        List<String> list = Arrays.asList(arr);
        System.out.println("Arrays.asList转List,只运行查看操作"+list.toString());
        List<String> list1 = new ArrayList<>();
        Collections.addAll(list1, arr);
        System.out.println("Collections.addAll,通过new一个List,可以进行增删改操作"+list1.toString());
        //基本数据数组转list
        List<Integer> intList = Arrays.stream(intArr).mapToObj(Integer::new).collect(Collectors.toList());
        System.out.println("mapToObj基本数据数组转list"+intList.toString());
    }
    
    private static List<DemoEntity> initData() throws ParseException{
        List<DemoEntity> initDatas = new ArrayList<>();
        for (int i = 0;i < 5;i++) {
            DemoEntity demo = new DemoEntity();
            demo.setId(i+1);
            demo.setName("TOM_" + i);
            demo.setBirthDate(new Date());
            demo.setAge(5*(i+1));
            demo.setSex('M');
            initDatas.add(demo);
        }
        //重复数据
        String dateString = "1964-09-30";
        Date date= new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
        DemoEntity demoF1 = new DemoEntity();
        demoF1.setId(6);
        demoF1.setName("Monica");
        demoF1.setBirthDate(date);
        demoF1.setBrief("球花");
        demoF1.setAge(59);
        demoF1.setSex('F');
        initDatas.add(demoF1);
        DemoEntity demoF2 = new DemoEntity();
        demoF2.setId(6);
        demoF2.setName("Monica");
        demoF2.setBirthDate(date);
        demoF2.setBrief("球花");
        demoF2.setAge(59);
        demoF2.setSex('F');
        initDatas.add(demoF2);
        //年龄为空
        DemoEntity demoF3 = new DemoEntity();
        demoF3.setId(6);
        demoF3.setName("Monica");
        demoF3.setBirthDate(date);
        demoF3.setBrief("球花");
        demoF3.setSex('F');
        initDatas.add(demoF3);
        System.out.println("初始数据-----------------------------------");
        initDatas.forEach(demo->System.out.println(demo.toString()));
        return initDatas;
    }
}

package com.renxiaozhao.service.demo.stream;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class DemoEntity {
    @ApiModelProperty(value = "主键")
    private Integer id;
    
    @ApiModelProperty(value = "姓名")
    private String name;
    
    @ApiModelProperty(value = "性别:男-M 女-F")
    private char sex;
    
    @ApiModelProperty(value = "年龄")
    private Integer age;
    
    @ApiModelProperty(value = "简介")
    private String brief;
    
    @ApiModelProperty(value = "生日")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthDate;
}

执行结果

初始数据-----------------------------------
DemoEntity(id=1, name=TOM_0, sex=M, age=5, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
DemoEntity(id=2, name=TOM_1, sex=M, age=10, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
DemoEntity(id=3, name=TOM_2, sex=M, age=15, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
DemoEntity(id=4, name=TOM_3, sex=M, age=20, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
DemoEntity(id=5, name=TOM_4, sex=M, age=25, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
DemoEntity(id=6, name=Monica, sex=F, age=59, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
DemoEntity(id=6, name=Monica, sex=F, age=59, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
DemoEntity(id=6, name=Monica, sex=F, age=null, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
过滤brief为空后的数据-----------------------------------
DemoEntity(id=6, name=Monica, sex=F, age=59, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
DemoEntity(id=6, name=Monica, sex=F, age=59, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
DemoEntity(id=6, name=Monica, sex=F, age=null, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
最大年龄=59,最小年龄=5
去重后统计大于30岁的人数=1
list转map key冲突时覆盖前面的key值设置,详细数据如下:
key = 1, value = DemoEntity(id=1, name=TOM_0, sex=M, age=5, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
key = 2, value = DemoEntity(id=2, name=TOM_1, sex=M, age=10, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
key = 3, value = DemoEntity(id=3, name=TOM_2, sex=M, age=15, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
key = 4, value = DemoEntity(id=4, name=TOM_3, sex=M, age=20, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
key = 5, value = DemoEntity(id=5, name=TOM_4, sex=M, age=25, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)
key = 6, value = DemoEntity(id=6, name=Monica, sex=F, age=null, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)
distinct去重
list转Map,按照id分组
key = 1, value = [DemoEntity(id=1, name=TOM_0, sex=M, age=5, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)]
key = 2, value = [DemoEntity(id=2, name=TOM_1, sex=M, age=10, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)]
key = 3, value = [DemoEntity(id=3, name=TOM_2, sex=M, age=15, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)]
key = 4, value = [DemoEntity(id=4, name=TOM_3, sex=M, age=20, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)]
key = 5, value = [DemoEntity(id=5, name=TOM_4, sex=M, age=25, brief=null, birthDate=Fri Jul 07 13:23:24 CST 2023)]
key = 6, value = [DemoEntity(id=6, name=Monica, sex=F, age=59, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964), DemoEntity(id=6, name=Monica, sex=F, age=null, brief=球花, birthDate=Wed Sep 30 00:00:00 CST 1964)]
新list:[TOM_0, TOM_1, TOM_2, TOM_3, TOM_4, Monica, Monica, Monica]
新list去重:[TOM_0, TOM_1, TOM_2, TOM_3, TOM_4, Monica]
list.toarray转数组[TOM_0, TOM_1, TOM_2, TOM_3, TOM_4, Monica, Monica, Monica]
list通过stream转数组[1, 2, 3, 4, 5, 6, 6, 6]
Arrays.asList转List,只运行查看操作[TOM_0, TOM_1, TOM_2, TOM_3, TOM_4, Monica, Monica, Monica]
Collections.addAll,通过new一个List,可以进行增删改操作[TOM_0, TOM_1, TOM_2, TOM_3, TOM_4, Monica, Monica, Monica]
mapToObj基本数据数组转list[1, 2, 3, 4, 5, 6, 6, 6]

在这里插入图片描述

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

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

相关文章

阿里云绑定域名

在阿里云安全组与宝塔安全放开8081端口 server {listen 8081;server_name www.whxyyds.top;charset utf-8;location / {root /home/ruoyi/projects/ruoyi-ui;try_files $uri $uri/ /index.html;index index.html index.htm;}location /prod-api/ {proxy_set_header …

途乐证券|A股自动驾驶概念“夏日躁动”

进入7月以后&#xff0c;A股智能汽车产业链——尤其是自动驾驶板块&#xff0c;开始逐渐收复去年失地。 香港途乐证券有限公司&#xff08;191883.com&#xff09;是香港最优秀的股票投资平台&#xff0c;平台致力于为投资者提供专业、安全、诚信的股票策略服务&#xff0c;通过…

微信内置h5浏览器 getBrandWCPayRequest支付

目录 getBrandWCPayRequest支付 什么是getBrandWCPayRequest支付&#xff1f; 如何使用getBrandWCPayRequest支付&#xff1f; getBrandWCPayRequest支付的特点和优势 结论 WeixinJSBridge&#xff1a;微信浏览器的JavaScript桥接工具 WeixinJSBridge的作用 WeixinJSBri…

【震惊】Top1清华考研985考研专业课惨遭团灭!

原谅我今天用了个“UC的标题”&#xff0c;只是他真的太令我震惊了&#xff01;&#xff08;请本次事件受影响者&#xff0c;务必看到最后&#xff0c;我会给出我的建议&#xff09; 事情的起因这样的&#xff1a;这周二有同学发我一条通知&#xff0c;清华大学通信考研考试科…

关于DBC文件的创建增加几点补充

上一节说了&#xff1a;DBC文件的简介与创建 这一节补充几点&#xff1a;关于DBC文件的创建增加几点补充 关于节点地址的定义和修改 有些朋友发现新建某个节点的时候&#xff0c;address栏的内容是灰色的&#xff0c;无法进行定义和修改 这个数值的更改不是在这里进行设置的…

18.ADC模数转换

1.STM32ADC简介&#xff1a; ADC(Analog to Digital Converter)即模数转换器&#xff0c;它可以将模拟信号转换成数字信号。按照其转换原理主要分为逐次逼近型、双积分型、电压频率转换型三种。 STM32 ADC主要特性&#xff1a; 12位分辨率&#xff1b;转换结束、注入…

Vue基础 -- 生命周期 数据共享

1 组件的生命周期 1.1 生命周期 & 生命周期函数 生命周期&#xff08;Life Cycle&#xff09;是指一个组件从创建 -> 运行 -> 销毁的整个阶段&#xff0c;强调的是一个时间段。 生命周期函数&#xff1a;是由 vue 框架提供的内置函数&#xff0c;会伴随着组件的生命…

UNI-APP_vmin横屏适配问题

vmax和vmin vmax 相对于视口的宽度或高度中较大的那个。其中最大的那个被均分为100单位的vmax vmin 相对于视口的宽度或高度中较小的那个。其中最小的那个被均分为100单位的vmin当竖屏布局时750rpx是竖屏布局屏幕的宽度 vmin不管横竖屏的情况下&#xff0c;100vmin都是手机屏幕…

Web漏洞-敏感信息泄露-Git操作

实验目的 熟悉常见git常见操作&#xff0c;如上传、回归、修改仓库等操作。 实验环境 git操作服务器&#xff0c;1台 web安全操作机&#xff0c;1台&#xff08;可选&#xff09; 实验内容 1.安装Git&#xff1a;sudo apt-get install git 2.安装Apache&#xff0c;为了模…

机器学习技术(二)——Python科学运算模块(Numpy、Pandas)

机器学习技术&#xff08;二&#xff09;——Python科学运算模块&#xff08;Numpy、Pandas&#xff09; 文章目录 机器学习技术&#xff08;二&#xff09;——Python科学运算模块&#xff08;Numpy、Pandas&#xff09;一、Numpy1、介绍、安装与导入2、Numpy常用操作 二、Pan…

Java面向对象程序开发——多线程开发

文章目录 前言多线程多线程的实现①、继承Thread类Thread常用方法Thread的构造器优缺点 ②、实现Runnable接口优缺点 ③、实现Callable接口Runnable接口和继承Thread类的区别 线程同步机制volatile同步锁 同步方法lock锁 线程池 前言 线程(thread)是一个程序内部的一条执行路径…

shared_ptr产生内存泄漏的场景

使用 shared_ptr 可以帮助管理动态分配的内存&#xff0c;它使用引用计数的方式来跟踪共享对象的引用数量&#xff0c;当引用计数为零时&#xff0c;会自动释放内存。然而&#xff0c;shared_ptr 也存在一些潜在的内存泄漏的场景&#xff0c;下面是一些常见的情况&#xff1a; …

LVS和keepa lived群集

keepa lived 简述 一.keepalived 服务重要功能 1管理LS负载均衡器软件 keepalived可以通过读取自身的配置文件&#xff0c;实现通过更底层的接口直接管理Lvs配置以及服务的启动 停止功能 这会使 LVS应用跟更加简便 2 支持故障自动切换 (failover) ①两台知己同时安装好kee…

网络字节序和套接字

4.1主机字节序列和网络字节序列 主机字节序列分为&#xff1a;大端字节序和小端字节序 大端&#xff1a;高位字节存储在内存的低地址处&#xff0c;低位字节存储在内存的高地址处。 小端&#xff1a;高位字节存储在内存的高地址处&#xff0c;低位字节存储在内存的低地址处。…

【算法基础】数据结构

链表 单链表 826. 单链表 - AcWing题库 #include<bits/stdc.h> using namespace std; const int N 100010; int m; int e[N],ne[N];//记录数据和下一结点坐标 int head,idx;//当前指向的结点 void init() {head-1;idx0; } void addtohead(int x) {e[idx]x;ne[idx]hea…

前端框架Vue

Vue 介绍 官方网站&#xff1a;https://cn.vuejs.org/ Vue.js是一种用于构建用户界面的开源JavaScript框架。它是一种轻量级的框架&#xff0c;易于学习和使用。它基于标准HTML&#xff0c;CSS和JavaScript构建&#xff0c;并提供了一套生声明式的&#xff0c;组件时的编程模…

【深入浅出 Spring Security(十三)】使用 JWT 进行前后端分离认证(附源码)

使用 JWT 进行前后端分离认证 一、JWT 的简单介绍二、使用 JWT 进行安全认证后端结合SpringSecurity实现前端Vue3结合Pinia、Axios实现测试结果 一、JWT 的简单介绍 JWT 全称 Java web Token&#xff0c;在此所讲述的是 JWT 用于身份认证&#xff0c;用服务器端生成的JWT去替代…

spring--Ioc控制反转/DI依赖注入

IOC控制反转-解耦 1.概念&#xff1a;在使用对象的时候&#xff0c;由主动的new转换为外部提供对象&#xff0c;将对象创建的控制权交给外部&#xff0c;即控制反转 2.spring提供了一个容器&#xff0c;称为IOC容器&#xff0c;用来从当ioc中的外部 3.被管理或者被创建的对象在…

ChatGPT实战:如何规划自己的职业生涯?

ChatGPT的出现&#xff0c;不仅改变了人们对人工智能技术的认识&#xff0c;也对经济社会发展产生了深远的影响。那么&#xff0c;在ChatGPT时代&#xff0c;人们应该如何规划自己的职业呢&#xff1f; 职业规划是一个有意义且重要的过程&#xff0c;它可以帮助你在职业生涯中…

什么是BI可视化?企业管理决策为什么要用BI系统?

在当今的商业环境中&#xff0c;数据已经成为企业决策制定的重要基础。然而&#xff0c;面对海量的数据&#xff0c;如何有效地分析和利用这些数据&#xff0c;成为了企业管理者面临的一大挑战。BI(Business Intelligence)系统应运而生&#xff0c;它可以帮助企业管理者从复杂的…