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

相关文章

  • spring中的懒加载详细解读

    spring中的懒加载详细解读

    这篇文章主要介绍了spring中的懒加载详细解读,如果某个Bean再程序运行周期中都可能不会被适用,那么可以设定该Bean为懒加载,优势是尽量节省了服务器的资源,缺点是可能会导致某个相应的时间增加,需要的朋友可以参考下
    2023-10-10
  • 基于指针pointers和引用references的区别分析

    基于指针pointers和引用references的区别分析

    本篇文章介绍了,基于指针pointers和引用references的区别分析。需要的朋友参考下
    2013-05-05
  • Java基础入门篇之逻辑控制练习题与猜数字游戏

    Java基础入门篇之逻辑控制练习题与猜数字游戏

    猜数字游戏是一款经典的游戏,该游戏说简单也很简单,说不简单确实也很难,这篇文章主要给大家介绍了关于Java基础入门篇之逻辑控制练习题与猜数字游戏的相关资料,需要的朋友可以参考下
    2023-06-06
  • 深入理解Spring事务的传播行为

    深入理解Spring事务的传播行为

    Spring在TransactionDefinition接口中规定了7种类型的事务传播行为。下面这篇文章主要给大家介绍了关于Spring事务传播行为的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-02-02
  • 如何用Java的swing编写简单计算器

    如何用Java的swing编写简单计算器

    这篇文章主要给大家介绍了关于如何用Java的swing编写简单计算器的相关资料,通过本文可以设计一个图形界面的简易计算器,完成简单的算术运算符,可以完成加法、减法、乘法、除法和取余运算,需要的朋友可以参考下
    2023-12-12
  • Java Swing JButton按钮的实现示例

    Java Swing JButton按钮的实现示例

    这篇文章主要介绍了Java Swing JButton按钮的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • SpringBoot整合aop面向切面编程过程解析

    SpringBoot整合aop面向切面编程过程解析

    这篇文章主要介绍了SpringBoot整合aop面向切面编程过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • 详解Java注解实现自己的ORM

    详解Java注解实现自己的ORM

    这篇文章主要介绍了Java注解实现自己的ORM知识,本文通过示例代码给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2022-10-10
  • spring中BeanUtils.copyProperties的使用(深拷贝,浅拷贝)

    spring中BeanUtils.copyProperties的使用(深拷贝,浅拷贝)

    本文主要介绍了spring中BeanUtils.copyProperties的使用(深拷贝,浅拷贝),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-05-05
  • JavaCV实现将视频以帧方式抽取

    JavaCV实现将视频以帧方式抽取

    这篇文章主要为大家详细介绍了JavaCV实现将视频以帧方式抽取,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-07-07

最新评论