Java 8中List转Map的多种方式

Java8流List转Map 阅读详情
AI摘要

文章展示了如何使用Java8的StreamAPI和Collectors将List<Student>转换成不同类型的Map,包括Map<String,String>,Map<String,Student>以及Map<String,List<Student>>,并处理了键的重复情况和对象分组。,

首先创建两个实体类

@Data
public class Student {
   //学号
    private  String no;  
    //姓名
    private  String name;	
}

@Data
public class Teacher{
    //教师号
    private  String no; 
    //姓名 
    private  String name; 
}

一、List<Object> 转 Map<String, String>

//声明一个List集合
List<Student> list = new ArrayList();  
	 list.add(new Student("1001", "小A"));  
	 list.add(new Student("1001", "小B"));//学号重复(下面特殊处理)
	 list.add(new Student("1002", "小C"));
	 list.add(new Student("1003", "小D"));
       
//将list转map 【key为1个属性,value为1个属性】  
Map<String, String> map =
	list.stream().collect(Collectors.toMap( 
		Student::getNo, 
		Student::getName,
	    (key1 , key2) -> key1  //(map的键重复不会报错,下面已经处理)
	));
	
//将list转map 【key为多个属性,value为1个属性】  
Map<String, String> map =
	list.stream().collect(Collectors.toMap( 
		obj -> obj.getNo() + "_" + obj.getName(),
		Student::getName,
	    (key1 , key2) -> key1   //(map的键重复不会报错,下面已经处理)
));

二、List<Object> 转 Map<String, Object> (返回对象本身)

//声明一个List集合
List<Student> list = new ArrayList();
	list.add(new Student("1001", "小A"));
	list.add(new Student("1001", "小B"));
	list.add(new Student("1002", "小C"));
	list.add(new Student("1003", "小D"));

//将list转map 【key为1个属性,value为对象本身】  (map的键去重)
Map<String, Student> map = 
 	list.stream().collect(Collectors.toMap( 
	 	Student::getNo, 
	    obj -> obj, 
	    (key1 , key2) -> key1 
    ));
    
或者

//将list转map 【key为1个属性,value为对象本身】  (map的键去重)
Map<String, Student> map = 
 	list.stream().collect(Collectors.toMap( 
	 	Student::getNo, 
	    Function.identity(), 
	    (key1 , key2) -> key1 
));
    
或者

//将list转map 【key为多个属性,value为对象本身】 (map的键去重)
Map<String, Student> map = 
 	list.stream().collect(Collectors.toMap( 
	 	obj -> obj.getNo() + "_" + obj.getName(),
	    obj -> obj, 
	    (key1 , key2) -> key1 
    ));
	

三、List<Object1> 转 Map<String, Object2> (返回另一个对象)

//声明一个List集合
List<Student> list = new ArrayList();
	list.add(new Student("1001", "小A"));
	list.add(new Student("1001", "小B"));
	list.add(new Student("1002", "小C"));
	list.add(new Student("1003", "小D"));

//将list转map 【key为1个属性,value为另一个对象】 (map的键去重)
Map<String, Teacher> map = 
	list.stream().collect(Collectors.toMap(
	    Student::getNo, 
		stu -> {
            Teacher teacher = new Teacher();
            teacher.setNo(stu.getNo());
            teacher.setName(stu.getName());
            return teacher;
        },  
        (key1 , key2) -> key1
));

四、List<Object> 转 Map<String, List<Object>> (分组)【以1个字段分/以多个字段分】

//声明一个List集合
List<Student> list = new ArrayList();
   list.add(new Student("1001", "小A"));
   list.add(new Student("1001", "小B"));
   list.add(new Student("1002", "小C"));
   list.add(new Student("1003", "小D"));

//将list转map  【key为1个属性,value为相同key的集合】 (以某1个属性来分组,将分组后相同的对象放在一起)
Map<String, List<Student>> map = 
   list.stream().collect( Collectors.groupingBy(Student::getNo) );


//将list转map 【key为多个属性,value为相同key的集合】 (以多个属性来分组,将分组后相同的对象放在一起)
Map<String, List<Student>> map = 
   list.stream().collect( Collectors.groupingBy(obj -> obj.getNo + "_" + obj.getName) );

jdk7 模仿 lambda 的 list转map工具 ,list之间比对属性key 并赋值value的工具类 jdk7 由于不支持 lambda表达式,不能使用jdk8的Stream编程 ,在开发过程中遇到stream能够轻松解决的问题,也会比较绕。 看到网上有内部类替代lamdba 中一些箭头函数或者Function ,Consumer 的地方; 后面发现之前的做的集合工具类主要用的是范型, 并不是十分依赖lambda。 按jdk8定义了常用的两个接口 Function ,Consumer p... 阅读详情

相关推荐

Java 8 Stream API实战:List转Map的多种方式与最佳实践

在Java编程中,集合操作是数据处理的基础,而Map作为核心数据结构,以其O(1)时间复杂度的键值查找能力,在缓存、索引和快速访问场景中不可或缺。其原理是通过哈希函数将键映射到存储位置,从而实现高效检索。Java 8引入的Stream API和Lambda表达式,将集合操作从命令式迭代升级为声明式函数式编程,极大地提升了代码的表达力和简洁性。通过Collectors.toMap和Collectors.groupingBy等收集器,开发者可以优雅地实现List到Map的转换,处理重复键、空值等边界情况,并支持

weixin_34098209的博客 340

Java8中List转Map的几种方式

Java8中List转Map的几种方式

风水道人 2万+

Java8中map转list

map转list可以称呼为map的扁平化(flatMap)处理,可以将一个map结构的数据转换为一个list结构的数据。通常在Java8的函数式编程中,经常需要将map转换成list的数据结构。在实际开发中,经常需要对map进行操作,如map的遍历、map的排序等等。数字集合List是我们在开发中使用较多的数据结构之一。map转list则可以让我们更加方便的对map进行操作。

qq_50523945的博客 2595

Java8:list转Map

Java8 List转Map; Map voMap = appVOList.stream().collect(Collectors.toMap(ApplicationVO::getAppId, Function.identity(), (key1, key2) -> key2));

清晨qc的博客 1万+

java List转Map的三种方法(java8语法特性使用)

java List转Map的三种方法(java8语法特性使用)

猿小白的博客 3208

手把手教你用FPGA实现SerDes高速接口设计(附避坑指南)

本文是一份详尽的FPGA SerDes高速接口设计实战指南。文章深入剖析了SerDes硬核(如GTX/GTH)的时钟管理、发送端均衡、接收端CDR与均衡等核心模块,并提供了Verilog代码示例。重点分享了信号完整性分析、眼图调试与误码率测试等实战经验,附有自定义高速视频流接口的完整实现案例与避坑指南,帮助工程师从“会用”到“懂”且能独立驾驭高速接口设计。

ik678901234的博客 1144

Java8 Stream API 集合操作(list 转 map 多种方式)

jdk8 stream流常用操作

huangli的博客 1526

ThingsBoard入门实战(二):ThingsBoard 设备接入

文章目录ThingsBoard 设备接入一、设备配置/设备类型二、设备三、设备接入HTTPCOAPMQTT四、下一步 ThingsBoard 设备接入 设备接入并不一定需要真正的设备,我们可以通过程序。或者命令来模拟设备,向平台发送信息。 这节我们先为用户分配一个设备,然后通过模拟设备命令更新设备的状态(遥测值)。 一、设备配置/设备类型 添加一个叫"路灯"的设备配置。 设备配置听起来比较抽象,可以认为是设备类型或者是设备类型的配置。实际上,ThingsBoard 中很多时候让选择设备类型,就是选的这个。

AIGC搞起 1万+

java8中map转string_jdk8的特性stream().map()将对象转换成另一个对象

java8的optional的使用:http://www.jdon.com/idea/java/using-optional-effectively-in-java-8.htmlhttp://www.runoob.com/java/java8-optional-class.htmlOptional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get(...

weixin_39560604的博客 7311

中兴FTTR光猫变简易OLT:低成本搭建全光监控与局域网实战指南

本文详细介绍了如何将中兴FTTR光猫改造为简易OLT设备,实现低成本全光监控与局域网扩展。通过LOID认证、桥接模式设置及终端数破解,用户可利用二手设备搭建高性能光纤网络,适用于远程监控和长距离组网场景,显著降低部署成本。

chair的专栏 2021

西南科技大学模拟电子技术实验二(二极管特性测试及其应用电路)预习报告

3、用二极管正向虚拟IV仪测出数据,并记录数据于虚表3和虚表4。1、按照指导书multisim仿真软件上画出三种模型电路图,1、按照指导书multisim仿真软件上画出三种模型电路图,1、按照指导书multisim仿真软件上画出三种模型电路图,表6 二极管三种模型参数测试表(电源电压=1.2V)2、用万用表测出数据,并记录数据于虚表1和虚表2。2、用万用表测出数据,并记录数据于虚表5和虚表6。表5 二极管三种模型参数测试表(电源电压=12V)二极管三种模型参数测试表(电源电压=12V)

Welcome To My6n Blog 4078

【JDK 8特性】快速将List转为Map、分组、过滤、求和

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34310785的博客 580

学Simulink--基于高比例可再生能源渗透的复杂电网建模场景实例:新能源高渗透下传统同步机主导系统的动态响应建模

摘要:本文详细介绍使用MATLAB/Simulink构建高比例可再生能源渗透的电网系统模型。主要内容包括:系统结构设计(新能源发电、同步发电机、电网等模块)、详细建模步骤(从创建项目到集成各模块)、关键控制算法实现(如MPPT和调速器控制)以及仿真分析。通过该模型可研究新能源高渗透率下传统同步机系统的动态响应特性,为电力系统稳定性分析提供有效工具。文章包含示例代码和典型仿真结果,展示了频率、电压等关键参数的稳定性表现。

xiaoheshang_123的博客 86

Java8中list转map方法总结

背景 在最近的工作开发之中,慢慢习惯了很多Java8中的Stream的用法,很方便而且也可以并行的去执行这个流,这边去写一下昨天遇到的一个list转map的场景。 list转map在Java8中stream的应用 常用方式 1.利用Collectors.toMap方法进行转换 public Map&lt;Long, String&gt; getIdNameMap(...

zlj1217的博客 20万+

基于Cesium移动的天空云

天空中的云朵也算是一种天气气候的效果,它能更加逼真的反映当前的天气状况,可以是白云朵朵,也可以是乌云密布,结合其他天气效果,可以组合形成较为真实的三维可视化场景。

星云数海的博客,一个专注GIS十多年的GISer人。 446

STM32实战开发(66):STM32图像处理开发教程

随着物联网、人工智能和嵌入式技术的不断发展,图像处理技术在嵌入式系统中的应用越来越广泛。图像处理不仅在视觉识别、安防监控、智能家居等领域中发挥着重要作用,也在工业自动化、医疗成像、无人驾驶等高科技领域中占据重要地位。而STM32凭借其强大的硬件性能和丰富的外设支持,成为了许多图像处理应用的理想平台。

2201_76125393的博客 1444

Java8遍历Map、Map转List、List转Map

遍历Map Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(2, "b"); map.put(3, "c"); // Map.keySet遍历 for (Integer k : map.keySet()) { System.out.println(k + " ==>...

C3Stones 1万+

基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的农作物害虫检测系统(深度学习模型+UI界面+训练数据集)

随着人工智能技术在农业领域的深入应用,基于深度学习的害虫检测系统已成为智慧农业的重要组成部分。本文详细介绍了一种基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的农作物害虫检测系统,涵盖算法原理、数据集构建、模型训练、系统实现及完整代码。该系统能够实时检测并识别多种农作物害虫,为农业生产提供精准的病虫害监测解决方案。

YOLO 273

Java8 Stream(11)List转Map

一、前言 开发中,List转Map是非常常见的操作,例如: List<T> 转 Map<String, T> List<T> 转 Map<String, List<T>> List<Map<String, Object>> 转 Map<String, List<Map<String, Object>>> 先造点数据: pigs.add(new Pig(1, "猪爸爸", 31, "M.

Java Spring Elasticsearch 4万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java 8 list to map_Java8中list转map

第一种: 取list中某2个字段作为Map的K,Vpublic Map getIdNameMap(Listaccounts) {returnaccounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));}第二种:将id和实体Bean做为K,Vpublic Map getIdAccountMap(L...

weixin_42386361的博客 4203

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Java实现List,Map,Set 遍历的多种方式

List的多种遍历方式,Map的多种遍历方式,Set的多种遍历方式

嘉禾嘉宁papa 7367

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Java 8 List转Map的几种方式

List 、Map 相互转换的几种方式: List 转 Map list 转 map , key是用户姓名,value是user对象, List<User> list = getUsers(); Map<String,User> userMap = Maps.newHashMap(); userMap = list.stream().collect(Collectors.toMap(User::getName, Function.identity())); list 转 map,k

liguangix的博客 2155

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

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

IT小白 46万+

java8 lamda表达式实现快速List转map,List进行分组,List按条件过滤

示例对象: public class Apple { private Integer id; private String name; private BigDecimal money; private Integer num; public Apple(Integer id, String name, BigDecimal money, Integer...

weikzhao0521的博客 1万+

Java 8 :List 转 Map 之 Collectors

总的来说,面试是有套路的,一面基础,二面架构,三面个人。最后,小编这里收集整理了一些资料,其中包括面试题(含答案)、书籍、视频等。希望也能帮助想进大厂的朋友加入社区:https://bbs.youkuaiyun.com/forums/4304bb5a486d4c3ab8389e65ecb71ac0案)、书籍、视频等。希望也能帮助想进大厂的朋友**[外链图片转存中…(img-43qvBAyd-1725635586423)][外链图片转存中…(img-D1bLMt0I-1725635586423)]

2401_86401114的博客 963
上一篇: SQL语句的加锁方式 - Mysql 锁机制
下一篇: git相关命令总结
splendor.s
博客等级 码龄10年 91粉丝 67原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值