java中实现list或set转map的方法
作者:lqh 时间:2023-11-06 18:04:11
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
标签:java,list,set,map
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android手势密码实现实例代码
2023-04-13 20:17:51
![](https://img.aspxhome.com/file/2023/6/125396_0s.png)
Socket结合线程池使用实现客户端和服务端通信demo
2023-01-21 20:23:50
![](https://img.aspxhome.com/file/2023/5/86835_0s.jpg)
使用springboot logback动态获取application的配置项
2023-09-03 21:21:41
Java真题实练掌握哈希表的使用
2023-11-09 06:33:15
![](https://img.aspxhome.com/file/2023/9/59079_0s.png)
java处理数据库不支持的emoji表情符问题解决
2021-08-21 00:16:58
GC算法实现垃圾优先算法
2023-11-07 17:25:15
![](https://img.aspxhome.com/file/2023/9/104709_0s.png)
如何在C#中集成Lua脚本
2021-12-24 23:24:35
![](https://img.aspxhome.com/file/2023/7/126097_0s.png)
Spring Security配置多个数据源并添加登录验证码的实例代码
2022-11-19 13:49:26
![](https://img.aspxhome.com/file/2023/6/69126_0s.png)
C#使用LINQ查询表达式的基本子句总结
2022-08-05 05:09:41
![](https://img.aspxhome.com/file/2023/3/77253_0s.png)
Java数据机构中关于并查集的详解
2022-09-05 13:23:53
![](https://img.aspxhome.com/file/2023/2/82982_0s.png)
Android App实现监听软键盘按键的三种方式
2021-09-14 10:39:27
![](https://img.aspxhome.com/file/2023/3/91703_0s.png)
解析在内部循环中Continue外部循环的使用详解
2023-09-24 08:03:50
List转换成DataSet实现代码
2023-03-02 04:46:01
JavaMail实现带附件的邮件发送
2021-10-21 15:00:09
![](https://img.aspxhome.com/file/2023/9/61919_0s.jpg)
Android自定义圆形倒计时进度条
2021-09-11 06:17:08
![](https://img.aspxhome.com/file/2023/4/101864_0s.gif)
C#字符串和Acsii码相互转换
2022-09-24 00:12:07
Java读取Map的两种方法与对比
2021-08-08 20:56:55
![](https://img.aspxhome.com/file/2023/3/65213_0s.png)
Android 调用系统相机拍摄获取照片的两种方法实现实例
2022-01-19 21:22:23
Java多线程 ThreadLocal原理解析
2022-11-15 12:48:50
SpringCloud之Config配置中心与Redis分布式锁详解
2023-12-21 02:14:41
![](https://img.aspxhome.com/file/2023/1/77961_0s.jpg)