java中实现list或set转map的方法
作者:lqh 发布时间:2023-11-06 18:04:11
标签:java,list,set,map
java中实现list或set转map的方法
在开发中我们有时需要将list或set转换为map(比如对象属性中的唯一键作为map的key,对象作为map的value),一般的想法就是new一个map,然后把list或set中的值一个个push到map中。
类似下面的代码:
List<String> stringList = Lists.newArrayList("t1", "t2", "t3");
Map<String, String> map = Maps.newHashMapWithExpectedSize(stringList.size());
for (String str : stringList) {
map.put(str, str);
}
是否还有更优雅的写法呢?答案是有的。
guava提供了集合(实现了Iterables接口或Iterator接口)转map的方法,方法定义如下:
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
* @since 10.0
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
这样我们就可以很方便的进行转换了,如下:
List<String> stringList = Lists.newArrayList("t1", "t2", "t3");
Map<String, String> map = Maps.uniqueIndex(stringList, new Function<String, String>() {
@Override
public String apply(String input) {
return input;
}
});
需要注意的是,如接口注释所说,如果Function返回的结果产生了重复的key,将会抛出异常。
java8也提供了转换的方法,这里直接照搬别人博客的代码:
@Test
public void convert_list_to_map_with_java8_lambda () {
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map<Integer, Movie> mappedMovies = movies.stream().collect(
Collectors.toMap(Movie::getRank, (p) -> p));
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
参考:https://www.jb51.net/article/104114.htm


猜你喜欢
- 前言:仿微信通讯录搜索功能,通过汉字或拼音首字母找到匹配的联系人并显示匹配的位置一:先看效果图字母索引搜索匹配二:功能分析1:汉字转拼音通讯
- Java 中HttpURLConnection附件上传的实例详解整合了一个自己写的采用Http做附件上传的工具,分享一下!示例代码:/**
- 发现问题原需求,在一个伸缩列表中,自定义LinearLayout继承LinearLayout动态添加布局。然而实现的时候:一共遍历了30条数
- Spring Boot FeignClient 捕获业务异常信息因项目重构采用spring cloud,feign不可避免。目前spring
- 一.前言Unity3D是如今最火爆的游戏开发引擎,它可以让我们能轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型的互动内容。它支持2
- c++换行符有哪些\n 换行,光标移到下一行的开头;endl,把缓冲槽的内容输出到控制台;\r 回车,光标移到当前行的开头,不会换到下一行,
- android客户端生成本地验证码主要用来限制用户随意按请求按钮,其实该示例也是来对自定义view的练练手而已,先给出效果图吧其中可定制:*
- 这篇文章主要介绍了Java类加载器ClassLoader用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值
- 前言大家或许在iOS程序开发中经常遇到屏幕旋转问题,比如说希望指定的页面进行不同的屏幕旋转,但由于系统提供的方法是导航控制器的全局方法,无法
- 不废话了,直接给大家贴代码了。class term { String str; int id; &
- 矢量室内地图开发因为公司项目的需要,需要开发一套室内地图,并实现路线的规划功能。因为之前没做过这方面的开发,相关的资料也比较少,所以只能一个
- 两种android图片裁剪方式,供大家参考,具体内容如下一、相机拍完照之后利用系统自带裁剪工具进行截取public static void
- 项目要求1.初次打开程序时右上角标题栏显示“无连接”,点击旁边的按钮选择“我的好友”,进入配对界面;2.选择好友之后,返回主界面,标题栏会显
- 废话不多说,先看下实现后的效果:实现思路看到上边 gif 图的效果,主要列举一下实现过程过程中遇到的难点。如何使键盘弹出时候不遮挡底部登录布
- 本文实例为大家分享了unity绘制一条流动弧线的具体代码,供大家参考,具体内容如下最终效果把下面脚本复制,直接拖上脚本,设置两个点(物体)的
- 本文为大家介绍了java图片添加水印实例代码,java实现水印还是非常方便的,水印可以是图片或者文字,具体内容如下package micha
- 手动将本地jar添加到Maven仓库将jar添加到本地仓库的做法以下面pom.xml依赖的jar包为例:实际项目中pom.xml依赖写法:&
- 最近在公司,项目不是很忙了,偶尔看见一个兄台在CSDN求助,帮忙要一个自定义的渐变色进度条,我当时看了一下进度条,感觉挺漂亮的,就尝试的去自
- (一)打包与运行SpringBoot项目快速启动(Linux版)基于Linux (CenteroS7)安装JDK,且版本不低于打包时使用的J
- MyBatis 配置之集合的嵌套前言介绍在一些查询结果包装类中,包含一些 List 集合属性,使用 collection 标签可以声明该 L