java中实现list或set转map的方法

 更新时间:2017年01月24日 17:12:15   投稿:lqh  
这篇文章主要介绍了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

相关文章

  • Java代理模式(Proxy)实现方法详解

    Java代理模式(Proxy)实现方法详解

    这篇文章主要介绍了Java代理模式(Proxy)实现的相关资料,代理模式是一种结构型设计模式,通过引入代理对象来控制对目标对象的访问,代理模式的优点包括职责清晰、扩展性好、保护目标对象和增强功能,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-04-04
  • java键盘录入的方法举例详解

    java键盘录入的方法举例详解

    这篇文章主要给大家介绍了关于java键盘录入的相关资料,我们在写程序的时候,数据值都是固定的,但是实际开发中,数据值肯定是变化的,所以,把数据改进为键盘录入,提高程序的灵活性,需要的朋友可以参考下
    2023-10-10
  • @RequestBody,@RequestParam和@Param的区别说明

    @RequestBody,@RequestParam和@Param的区别说明

    这篇文章主要介绍了@RequestBody,@RequestParam和@Param的区别说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • MybatisPlus整合Flowable出现的坑及解决

    MybatisPlus整合Flowable出现的坑及解决

    这篇文章主要介绍了MybatisPlus整合Flowable出现的坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Java发送https请求并跳过ssl证书验证方法

    Java发送https请求并跳过ssl证书验证方法

    最近在负责一个对接第三方服务的事情,在对接期间因为第三方服务为https的请求,这篇文章主要给大家介绍了关于Java发送https请求并跳过ssl证书验证的相关资料,需要的朋友可以参考下
    2023-11-11
  • 理解Java的序列化与反序列化

    理解Java的序列化与反序列化

    这篇文章主要为大家详细介绍了Java的序列化与反序列化,序列化是一种对象持久化的手段。普遍应用在网络传输、RMI等场景中。本文通过分析ArrayList的序列化来介绍Java序列化的相关内容,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • MyBatis 源码分析 之SqlSession接口和Executor类

    MyBatis 源码分析 之SqlSession接口和Executor类

    mybatis框架在操作数据的时候,离不开SqlSession接口实例类的作用,下面通过本文给大家实例剖析MyBatis 源码分析之SqlSession接口和Executor类,需要的朋友参考下吧
    2017-02-02
  • RocketMQ存储文件的实现

    RocketMQ存储文件的实现

    这篇文章主要介绍了RocketMQ存储文件的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Maven配置单仓库与多仓库的实现(Nexus)

    Maven配置单仓库与多仓库的实现(Nexus)

    本文主要介绍了Maven配置单仓库与多仓库的实现(Nexus),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • MyBatis之insert主键自增和自定义主键详解

    MyBatis之insert主键自增和自定义主键详解

    本文介绍了如何使用MyBatis解决插入数据时因主键唯一性约束导致的错误问题,以及如何自定义主键生成规则,文中详细解释了如何在MyBatis中配置自增主键,并提供了测试示例
    2024-12-12

最新评论