首页 > 其他分享 >个人Stream常用操作

个人Stream常用操作

时间:2024-10-16 09:11:43浏览次数:1  
标签:常用 name Stream personList sex Person York 操作 New

1、list转map

我们可以使用 Collectors.toMap() 方法来实现。

  • Person对象类
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;  // 姓名
    private int salary; // 薪资
    private int age; // 年龄
    private String sex; //性别
    private String area;  // 地区

}

  • 测试转换方式一
@SpringBootTest
public class StreamDemoTest {
	@Test
	public void listToMapTest(){
		List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("Tom", 8900, 17,"male", "New York"));
		personList.add(new Person("Jack", 7000,18 ,"male", "Washington"));
		personList.add(new Person("Lily", 7800,20, "female", "Washington"));
		personList.add(new Person("Anni", 8200,22, "female", "New York"));
		personList.add(new Person("Owen", 9500,20, "male", "New York"));
		personList.add(new Person("Alisa", 7900,18, "female", "New York"));
		// 转换方式一
		Map<String, Person> personMap = personList.stream()
			.collect(Collectors.toMap(Person::getName, Function.identity()));
		for (Map.Entry<String, Person> entry : personMap.entrySet()) {
			System.out.println(entry);
		}
}

我们可以将名称作为key,将对象本体作为value,结果如下

Tom=Person(name=Tom, salary=8900, age=17, sex=male, area=New York)
Owen=Person(name=Owen, salary=9500, age=20, sex=male, area=New York)
Anni=Person(name=Anni, salary=8200, age=22, sex=female, area=New York)
Alisa=Person(name=Alisa, salary=7900, age=18, sex=female, area=New York)
Jack=Person(name=Jack, salary=7000, age=18, sex=male, area=Washington)
Lily=Person(name=Lily, salary=7800, age=20, sex=female, area=Washington)

但是这样转换如果有相同的key的话会报错 java.lang.IllegalStateException: Duplicate key XXXX


这种情况下我们可以使用Collectors.toMap() 的重载方法来进行转换

  • 测试转换方式二
    当我们的map中可能存在重复key的时候,我们可以使用 Collectors.toMap() 的重载方法,包含了一个 mergeFunction 合并函数来处理重复key数据。
@Test
public void listToMapTest(){
	List<Person> personList = new ArrayList<Person>();
	personList.add(new Person("Tom", 8900, 17,"男", "New York"));
	personList.add(new Person("Tom", 7000,18 ,"女", "Washington"));
	personList.add(new Person("Lily", 7800,20, "女", "Washington"));
	personList.add(new Person("Anni", 8200,22, "女", "New York"));
	personList.add(new Person("Tom", 9500,20, "男", "New York"));
	personList.add(new Person("Lily", 7900,18, "男", "New York"));
	// 转换为map时使用已存在数据
	Map<String, Person> personMap = personList.stream()
		.collect(Collectors.toMap(Person::getName, Function.identity(),
			(exists,newest)-> exists ));
	/*  ==================== 打印结果 =================
            Tom=Person(name=Tom, salary=8900, age=17, sex=male, area=New York)
            Anni=Person(name=Anni, salary=8200, age=22, sex=female, area=New York)
            Lily=Person(name=Lily, salary=7800, age=20, sex=female, area=Washington)
         */
	// 转换为map时使用最新的数据替换旧数据
	Map<String, Person> personMap1 = personList.stream()
		.collect(Collectors.toMap(Person::getName, Function.identity(),
			(exists,newest)-> newest ));
	/*  ==================== 打印结果 =================
            Tom=Person(name=Tom, salary=9500, age=20, sex=male, area=New York)
            Anni=Person(name=Anni, salary=8200, age=22, sex=female, area=New York)
            Lily=Person(name=Lily, salary=7900, age=18, sex=female, area=New York)
         */

	// 也可以进行判断后转换,当key重复时,如果最新数据性别为男则使用最新数据替换,否则使用已存在的旧数据
	Map<String, Person> personMap2 = personList.stream()
		.collect(Collectors.toMap(Person::getName, Function.identity(),
			(exists,newest)-> newest.getSex().equals("男") ? newest : exists));
	/*  ==================== 打印结果 =================
            Tom=Person(name=Tom, salary=9500, age=20, sex=男, area=New York)
            Anni=Person(name=Anni, salary=8200, age=22, sex=女, area=New York)
            Lily=Person(name=Lily, salary=7900, age=18, sex=男, area=New York)
        */
}

标签:常用,name,Stream,personList,sex,Person,York,操作,New
From: https://www.cnblogs.com/Snowclod/p/18468983

相关文章

  • linux 操作系统下 dpkg-preconfigure 命令介绍和使用案例
    linux操作系统下dpkg-preconfigure命令介绍和使用案例dpkg-preconfigure命令介绍dpkg-preconfigure是Debian和基于Debian的Linux发行版中用于预配置软件包的工具。它允许用户在安装软件包之前,提前提供配置选项,从而简化安装过程。命令格式dpkg-preconfigure[选......
  • 文件操作(下)
    目录文件的顺序读写顺序读写函数介绍fputcfgetcfputsfgetsfprintffscanffwritefread文件的随机读写fseekftellrewind文件读取结束的判定被错误使用的feoffeof文本文件的例子二进制文件的例子文件缓冲区文件的顺序读写顺序读写函数介绍fputcfputc的详细介绍......
  • 禁止拷贝构造函数和赋值操作符
     GlobalSettings(constGlobalSettings&)=delete;GlobalSettings&operator=(constGlobalSettings&)=delete;这两行代码是为了禁止拷贝构造函数和赋值操作符,也就是说,GlobalSettings 类的对象无法通过拷贝或赋值来创建或修改。这是为了防止类的实例被复制,通常用于实现单......
  • Selenium操作:测试form表单
    from表单是经常测试的用例,用户登录、注册等都会用到form表单,本文简单设计了一个用户登录的form表单,并对该form表单进行测试一、自定义form表单1、用到的组件如下图,图中定义了一个登录界面的form表单,用到的表单元素:type="text";type="submit"2、代码示例新建HTML文件文......
  • PetaLinux工程的常用命令——petalinux-create
    petalinux-create:此命令创建新的PetaLinux项目或组件。注:有些命令我没用过,瞎翻译有可能会翻译错了,像是和fpgamanager相关的部分。用法: petalinux-create[options]<-t|--type<TYPE><-n|--name<COMPONENT_NAME>必须参数: -t,--type<TYPE>      ......
  • python实现了通过摄像头检测手部动作,根据手指数量的不同映射为特定的视频控制操作
    importcv2#导入OpenCV库,用于图像处理importmediapipeasmp#导入MediaPipe库,用于手部检测等fromseleniumimportwebdriver#导入selenium库fromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.byimportByfromselenium.webdrive......
  • 例2.3列表操作示例
    '''首先先定义一个列表,列表是写在[]里,用逗号隔开的,元素是可以改变的列表的截取语法结构是:变量[头下标:尾下标]'''L=['abc',12,3.45,'python',2.789]#输出完整列表print(L)#输出列表的第一个元素print(L[0])#将列表的第一个元素修改为‘a’L[0]='a'#将列表的第2个元素到第3个元素......
  • leetcode 刷题day43动态规划Part12(115.不同的子序列、583. 两个字符串的删除操作、72.
    115.不同的子序列思路:这个题还是比较有难度的,问题s中有多少个t子序列可以转化为s字符串中有多少删除元素的方式,使s可以变成t。考虑动规五部曲。1、确定dp数组(dptable)以及下标的含义dp[i][j]:以i-1为结尾的s子序列中出现以j-1为结尾的t的个数为dp[i][j]。2、确定递推公式......
  • union all SQL 操作符
    在Hive中,`UNIONALL`是一个SQL操作符,用于将两个或多个查询的结果合并为一个结果集。与`UNION`不同,`UNIONALL`不会自动去重,因此它会返回所有查询结果,包括重复的记录。以下是`UNIONALL`在Hive中的一些主要作用和特点: 主要作用1.合并结果集:  可以将多个S......
  • 灾难恢复:邮箱数据库操作总结:整理 查询邮箱数据库大小和空白数据大小(重要文档)
    灾难恢复:邮箱数据库操作总结:整理查询邮箱数据库大小和空白数据大小(重要文档)邮箱数据库整理查询邮箱数据库大小和空白数据大小AvailableNewMailboxSpace是指的这个总空间里可以被“减肥”掉的空间。Get-MailboxDatabase db0* -Status|FTName,@{n="MailboxCount";e={(Get-M......