Java 8 的List<V> 转成 Map<K, V>

问题: Java 8 的List 转成 Map<K, V>

我想要使用Java 8的streams和lambdas转换一个 List 对象为 Map

下面是我在Java 7里面的写法

private Map<String, Choice> nameMap(List<Choice> choices) {final Map<String, Choice> hashMap = new HashMap<>();for (final Choice choice : choices) {hashMap.put(choice.getName(), choice);}return hashMap;
}

我可以很轻松地用Java8和Guava搞定,但是呢我又不知道怎么不用Guava搞定

Guava写法:

private Map<String, Choice> nameMap(List<Choice> choices) {return Maps.uniqueIndex(choices, new Function<Choice, String>() {@Overridepublic String apply(final Choice input) {return input.getName();}});
}

Guava +Java 8 lambdas写法:

private Map<String, Choice> nameMap(List<Choice> choices) {return Maps.uniqueIndex(choices, Choice::getName);
}

回答一:

基于Collectors 文档,可以简写成为:

Map<String, Choice> result =choices.stream().collect(Collectors.toMap(Choice::getName,Function.identity()));

回答二

如果你的key不保证对于每个list中每个元素都是独一无二的,你就应该转换成Map<String, List>而不是Map<String, Choice>

Map<String, List<Choice>> result =choices.stream().collect(Collectors.groupingBy(Choice::getName));

回答三

用 getName() 作为 key 并且Choice 本身作为map的value:

Map<String, Choice> result =choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));

回答四

上述的大部分回答的忽略了一种情况了就是当list有重复元素的时候。这种情况下就会抛出 IllegalStateException,参考下面的代码去处理重复的list元素吧

public Map<String, Choice> convertListToMap(List<Choice> choices) {return choices.stream().collect(Collectors.toMap(Choice::getName, choice -> choice,(oldValue, newValue) -> newValue));}

回答五

例如你想转换对象的一些域到map上:

对象是:

class Item{private String code;private String name;public Item(String code, String name) {this.code = code;this.name = name;}//getters and setters}

List 转 Map的操作是:

List<Item> list = new ArrayList<>();
list.add(new Item("code1", "name1"));
list.add(new Item("code2", "name2"));Map<String,String> map = list.stream().collect(Collectors.toMap(Item::getCode, Item::getName));

文章翻译自Stack Overflow:https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v

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

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

相关文章

已知两点坐标拾取怎么操作_已知的操作员学习-第4部分

已知两点坐标拾取怎么操作有关深层学习的FAU讲义 (FAU LECTURE NOTES ON DEEP LEARNING) These are the lecture notes for FAU’s YouTube Lecture “Deep Learning”. This is a full transcript of the lecture video & matching slides. We hope, you enjoy this as mu…

北京供销大数据集团发布SinoBBD Cloud 一体化推动产业云发展

9月5日&#xff0c;第五届全球云计算大会在上海世博展览馆盛大开幕&#xff0c;国内外顶尖企业汇聚一堂&#xff0c;新一代云计算技术产品纷纷亮相。作为国内领先的互联网基础服务提供商&#xff0c;北京供销大数据集团(以下简称“SinoBBD”)受邀参加此次大会&#xff0c;并正式…

windows下有趣的小玩意

1.显示文件和隐藏文件。在当前目录下shift右键 选择cmd命令 运行显示文件: attrib -s -h 文件名 隐藏文件: attrib -s h 文件名 2.查看电脑支持的最大内存 在cmd下运行wmic memphysical get maxcapacity所得结果单位mb 所得/1024/1024 得到单位G 3.windowsR 输入…

rxjs angular_Angular RxJS深度

rxjs angularIn this tutorial, well learn to use the RxJS 6 library with Angular 6 or Angular 7. Well learn about:在本教程中&#xff0c;我们将学习将RxJS 6库与Angular 6或Angular 7结合使用。我们将了解&#xff1a; How to import the Observable class and the ot…

HashMap, LinkedHashMap 和 TreeMap的区别

HashMap, LinkedHashMap 和 TreeMap的区别 Java里面的HashMap, LinkedHashMap 和 TreeMap 有什么区别?我看不出以下3个key和value有什么不同的。Hashtables里面又是怎么样的呢&#xff1f; Map m1 new HashMap(); m1.put("map", "HashMap"); m1.put(&q…

“陪护机器人”研报:距离真正“陪护”还差那么一点

一款有“缺陷”的机器人&#xff0c;怎能做到真正的“陪护”&#xff1f; 近日&#xff0c;鼎盛智能发布了一款名为Ibotn的&#xff08;爱蹦&#xff09;幼儿陪伴机器人&#xff0c;核心看点就是通过人脸识别、场景识别等计算机视觉技术来实现机器人对儿童的陪护。不过&#xf…

neo-6m uno_Uno-统治所有人的平台

neo-6m unoFirst, we should start off with what Uno is and why you should care. 首先&#xff0c;我们应该从Uno是什么以及为什么要关心开始。 As stated on their website, Uno is "The only platform for building native mobile, desktop and WebAssembly apps wi…

【转】消息队列应用场景

一、消息队列概述 消息队列中间件是分布式系统中重要的组件&#xff0c;主要解决应用耦合&#xff0c;异步消息&#xff0c;流量削锋等问题。实现高性能&#xff0c;高可用&#xff0c;可伸缩和最终一致性架构。是大型分布式系统不可缺少的中间件。 目前在生产环境&#xff0c;…

JDK和JRE区别是什么

问题&#xff1a;JDK和JRE区别是什么 他们的角色分别是什么&#xff1f;我们应该什么时候使用他们&#xff1f; 回答一 JRE是Java Runtime Environment&#xff08;Java运行时环境&#xff09;。它是一个包&#xff0c;集合了运行一个编译好的Java程序的一切必须的东西&…

树莓派新手入门教程

http://www.ruanyifeng.com/blog/2017/06/raspberry-pi-tutorial.html

lime 模型_使用LIME的糖尿病预测模型解释— OneZeroBlog

lime 模型Article outline文章大纲 Introduction 介绍 Data Background 资料背景 Aim of the article 本文的目的 Exploratory analysis 探索性分析 Training a Random Forest Model 训练随机森林模型 Global Importance 全球重要性 Local Importance 当地重要性 介绍 (Introd…

react 生命挂钩_如何在GraphQL API中使用React挂钩来管理状态

react 生命挂钩In this blog post, we are going to learn -在这篇博客中&#xff0c;我们将学习- What React hooks are 什么是React钩子 How to use hooks for state management 如何使用挂钩进行状态管理 Before we start working with hooks, let us take a brief moment …

Linux第三周作业

1.三个法宝 ①存储程序计算机工作模型&#xff0c;计算机系统最最基础性的逻辑结构&#xff1b; ②函数调用堆栈&#xff0c;堆栈完成了计算机的基本功能&#xff1a;函数的参数传递机制和局部变量存取 &#xff1b; ③中断&#xff0c;多道程序操作系统的基点&#xff0c;没有…

什么时候使用静态方法

问题&#xff1a;什么时候使用静态方法 I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I shou…

RESTful API浅谈

2019独角兽企业重金招聘Python工程师标准>>> 上半年时候&#xff0c;部门有组织的讨论了一下实践微服务的技术话题&#xff0c;主要内容是SOA服务和微服务各自的优势和难点&#xff0c;其中有提到关于RESTful API设计方法。 正好最近在深入的学习HTTP协议&#xff0…

spring自动注入--------

<?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema/beans"xmlns:p"http://www.springframework.org/schema/p"xmlns:c"http://www.springframework.org/schema/c"xmlns…

变量的作用域和生存期:_生存分析简介:

变量的作用域和生存期:In the previous article, I have described the Kaplan-Meier estimator. To give a quick recap, it is a non-parametric method to approximating the true survival function. This time, I will focus on another approach to visualizing a surviv…

数字孪生营销_如何通过数字营销增加您的自由职业收入

数字孪生营销There are a lot of ways we could go with this topic as it’s a huge one, but I just want to cover the nuggets here and make it simple as well as practical to understand and implement.我们可以采用很多方法来处理这个主题&#xff0c;因为它是一个很大…

您的网卡配置暂不支持1000M宽带说明

国内宽带网速越来越快&#xff0c;运营商更是在今年初纷纷推进千兆宽带业务。为了让用户更好地了解网络状况&#xff0c;360宽带测速器发布新版&#xff0c;优化了宽带测速范围&#xff0c;可有效支持最高1000&#xff2d;的带宽测量。此外&#xff0c;宽带测速器能检测用户网卡…

教辅的组成(网络流果题 洛谷P1231)

题目描述 蒟蒻HansBug在一本语文书里面发现了一本答案&#xff0c;然而他却明明记得这书应该还包含一份练习题。然而出现在他眼前的书多得数不胜数&#xff0c;其中有书&#xff0c;有答案&#xff0c;有练习册。已知一个完整的书册均应该包含且仅包含一本书、一本练习册和一份…