您的位置 首页 > 数码极客

普通的list集合如何转成map

在开发中我们有时需要将list或set转换为map(比如对象属性中的唯一键作为map的key,对象作为map的value),一般的想法就是new一个map,然后把list或set中的值一个个push到map中。

类似下面的代码:


  1. List<String> stringList = Li("t1", "t2", "t3");
  2. Map<String, String> map = Ma());
  3. for (String str : stringList) {
  4. map.put(str, str);
  5. }

是否还有更优雅的写法呢?答案是有的。

guava提供了集合(实现了Iterables接口或Iterator接口)转map的方法,方法定义如下:


  1. /**
  2. * Returns an immutable map for which the {@link Map#values} are the given
  3. * elements in the given order, and each key is the product of invoking a
  4. * supplied function on its corresponding value.
  5. *
  6. * @param values the values to use when constructing the {@code Map}
  7. * @param keyFunction the function used to produce the key for each value
  8. * @return a map mapping the result of evaluating the function {@code
  9. * keyFunction} on each value in the input collection to that value
  10. * @throws IllegalArgumentException if {@code keyFunction} produces the same
  11. * key for more than one value in the input collection
  12. * @throws NullPointerException if any elements of {@code values} is null, or
  13. * if {@code keyFunction} produces {@code null} for any value
  14. */
  15. public static <K, V> ImmutableMap<K, V> uniqueIndex(
  16. Iterable<V> values, Function<? super V, K> keyFunction) {
  17. return uniqueIndex(), keyFunction);
  18. }
  19. /**
  20. * Returns an immutable map for which the {@link Map#values} are the given
  21. * elements in the given order, and each key is the product of invoking a
  22. * supplied function on its corresponding value.
  23. *
  24. * @param values the values to use when constructing the {@code Map}
  25. * @param keyFunction the function used to produce the key for each value
  26. * @return a map mapping the result of evaluating the function {@code
  27. * keyFunction} on each value in the input collection to that value
  28. * @throws IllegalArgumentException if {@code keyFunction} produces the same
  29. * key for more than one value in the input collection
  30. * @throws NullPointerException if any elements of {@code values} is null, or
  31. * if {@code keyFunction} produces {@code null} for any value
  32. * @since 10.0
  33. */
  34. public static <K, V> ImmutableMap<K, V> uniqueIndex(
  35. Iterator<V> values, Function<? super V, K> keyFunction) {
  36. checkNotNull(keyFunction);
  37. Immu;K, V> builder = Immu();
  38. while ()) {
  39. V value = values.next();
  40. builder.pu(value), value);
  41. }
  42. return builder.build();
  43. }
  44. 这样我们就可以很方便的进行转换了,如下:
  45. List<String> stringList = Li("t1", "t2", "t3");
  46. Map<String, String> map = Ma(stringList, new Function<String, String>() {
  47. @Override
  48. public String apply(String input) {
  49. return input;
  50. }
  51. });

需要注意的是,如接口注释所说,如果Function返回的结果产生了重复的key,将会抛出异常。

java8也提供了转换的方法,这里直接照搬别人博客的代码:


  1. @Test
  2. public void convert_list_to_map_with_java8_lambda () {
  3. List<Movie> movies = new ArrayList<Movie>();
  4. movies.add(new Movie(1, "The Shawshank Redemption"));
  5. movies.add(new Movie(2, "The Godfather"));
  6. Map<Integer, Movie> mappedMovies = movies.stream().collect(
  7. Collec(Movie::getRank, (p) -> p));
  8. logger.info(mappedMovies);
  9. assertTrue() == 2);
  10. assertEquals("The Shawshank Redemption", ma(1).getDescription());

责任编辑: 鲁达

1.内容基于多重复合算法人工智能语言模型创作,旨在以深度学习研究为目的传播信息知识,内容观点与本网站无关,反馈举报请
2.仅供读者参考,本网站未对该内容进行证实,对其原创性、真实性、完整性、及时性不作任何保证;
3.本站属于非营利性站点无毒无广告,请读者放心使用!

“普通的list集合如何转成map,list集合如何排序,list集合如何去重,list集合如何判空”边界阅读