快捷搜索:  汽车  科技

java set集合怎么转换成list(java中list或set转map的方法)

java set集合怎么转换成list(java中list或set转map的方法)需要注意的是,如接口注释所说,如果Function返回的结果产生了重复的key,将会抛出异常。java8也提供了转换的方法,这里直接照搬别人博客的代码:

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

类似下面的代码:


  1. List<String> stringList = Lists.newArrayList("t1" "t2" "t3");
  2. Map<String String> map = Maps.newHashMapWithExpectedSize(stringList.size());
  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(values.iterator() 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. ImmutableMap.Builder<K V> builder = ImmutableMap.builder();
  38. while (values.hasNext()) {
  39. V value = values.next();
  40. builder.put(keyFunction.apply(value) value);
  41. }
  42. return builder.build();
  43. }
  44. 这样我们就可以很方便的进行转换了,如下:
  45. List<String> stringList = Lists.newArrayList("t1" "t2" "t3");
  46. Map<String String> map = Maps.uniqueIndex(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. Collectors.toMap(Movie::getRank (p) -> p));
  8. logger.info(mappedMovies);
  9. assertTrue(mappedMovies.size() == 2);
  10. assertEquals("The Shawshank Redemption" mappedMovies.get(1).getDescription());

java set集合怎么转换成list(java中list或set转map的方法)(1)

猜您喜欢: