国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java中實現list或set轉map的方法

2019-11-26 13:10:18
字體:
來源:轉載
供稿:網友

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

參考://m.survivalescaperooms.com/article/104114.htm

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 徐州市| 满城县| 高台县| 扬中市| 叙永县| 闵行区| 竹北市| 龙陵县| 阳江市| 顺义区| 上杭县| 蓬安县| 高邑县| 永安市| 丹东市| 大化| 南平市| 招远市| 鸡西市| 丰台区| 来宾市| 苏尼特右旗| 淮安市| 宽城| 霍邱县| 师宗县| 新干县| 济南市| 泾阳县| 新沂市| 建湖县| 蒙城县| 阳泉市| 盐边县| 全南县| 长宁县| 那坡县| 舞钢市| 加查县| 东平县| 临桂县|