欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java中實現(xiàn)list或set轉(zhuǎn)map的方法

 更新時間:2017年01月24日 17:12:15   投稿:lqh  
這篇文章主要介紹了java中實現(xiàn)list或set轉(zhuǎn)map的方法的相關(guān)資料,需要的朋友可以參考下

java中實現(xiàn)list或set轉(zhuǎn)map的方法

在開發(fā)中我們有時需要將list或set轉(zhuǎn)換為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); 
} 

是否還有更優(yōu)雅的寫法呢?答案是有的。

guava提供了集合(實現(xiàn)了Iterables接口或Iterator接口)轉(zhuǎn)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(); 
} 

這樣我們就可以很方便的進行轉(zhuǎn)換了,如下:

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返回的結(jié)果產(chǎn)生了重復的key,將會拋出異常。

java8也提供了轉(zhuǎn)換的方法,這里直接照搬別人博客的代碼:

@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());  
}  

參考:http://www.dbjr.com.cn/article/104114.htm

相關(guān)文章

  • Java的CopyOnWriteArrayList操作詳解

    Java的CopyOnWriteArrayList操作詳解

    這篇文章主要介紹了Java的CopyOnWriteArrayList操作詳解,  CopyOnWriteArrayList是ArrayList 的一個線程安全的變體,其中所有可變操作(add、set等等)都是通過對底層數(shù)組進行一次新的復制來實現(xiàn)的,需要的朋友可以參考下
    2023-12-12
  • springMVC在restful風格的性能優(yōu)化方案

    springMVC在restful風格的性能優(yōu)化方案

    這篇文章主要介紹了springMVC在restful風格的性能優(yōu)化方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 淺談Java自定義注解和運行時靠反射獲取注解

    淺談Java自定義注解和運行時靠反射獲取注解

    下面小編就為大家?guī)硪黄獪\談Java自定義注解和運行時靠反射獲取注解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-11-11
  • Java?CompletableFuture實現(xiàn)原理分析詳解

    Java?CompletableFuture實現(xiàn)原理分析詳解

    CompletableFuture是Java8并發(fā)新特性,本文我們主要來聊一聊CompletableFuture的回調(diào)功能以及異步工作原理是如何實現(xiàn)的,需要的可以了解一下
    2022-09-09
  • Java自定義實現(xiàn)鏈隊列詳解

    Java自定義實現(xiàn)鏈隊列詳解

    這篇文章主要為大家詳細介紹了Java自定義實現(xiàn)鏈隊列的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • 解決springboot環(huán)境切換失效的問題

    解決springboot環(huán)境切換失效的問題

    這篇文章主要介紹了解決springboot環(huán)境切換失效的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • JAVA?從完整的文件路徑中分別截取文件名和文件路徑的實現(xiàn)

    JAVA?從完整的文件路徑中分別截取文件名和文件路徑的實現(xiàn)

    在Java編程中,經(jīng)常會遇到需要截取文件名的場景,本文主要介紹了JAVA?從完整的文件路徑中分別截取文件名和文件路徑的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-04-04
  • 如何在Intellij中安裝LeetCode刷題插件方便Java刷題

    如何在Intellij中安裝LeetCode刷題插件方便Java刷題

    這篇文章主要介紹了如何在Intellij中安裝LeetCode刷題插件方便Java刷題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • Java Chassis3過載狀態(tài)下的快速失敗解決分析

    Java Chassis3過載狀態(tài)下的快速失敗解決分析

    本文解密了Java Chassis 3快速失敗相關(guān)的機制和背后故事,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • SpringSecurity安全管理開發(fā)過程

    SpringSecurity安全管理開發(fā)過程

    Spring?是一個非常流行和成功的?Java?應用開發(fā)框架,Spring?Security?基于?Spring?框架,提供了一套?Web?應用安全性的完整解決方案,這篇文章主要介紹了SpringSecurity安全管理,需要的朋友可以參考下
    2024-07-07

最新評論