java中实现list或set转map的方法

网友投稿 501 2023-06-16


java中实现list或set转map的方法

java中实现list或set转mahttp://p的方法

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

类似下面的代码:

List stringList = Lists.newArrayList("t1", "t2", "t3");

Map 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 ImmutableMap

Iterable 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 ImmutableMap uniqueIndex(

Iterator values, Function super V, K> keyFunction) {

checkNotNull(keyFunction);

ImmutableMap.Builder builder = ImmutableMap.builder();

while (values.hasNext()) {

V value = values.next();

builder.put(keyFunction.apply(value), value);

}

return builder.build();

}

这样我们就可以很方便的进行转换了,如下:

List stringList = Lists.newArrayList("t1", "t2", "t3");

Map map = Maps.uniqueIndex(stringList, new Function() {

@Override

public String apply(String input) {

return input;

}

});

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

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

@Test

public void convert_list_to_map_with_java8_lambda () {

List movies = new ArrayList();

movies.add(new Movie(1, "The Shawshank Redemption"));

movies.add(new Movie(2, "The Godfather"));

Map 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())zPtgUNlT;

}

参考://jb51.net/article/104114.htm

Iterable 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 ImmutableMap uniqueIndex(

Iterator values, Function super V, K> keyFunction) {

checkNotNull(keyFunction);

ImmutableMap.Builder builder = ImmutableMap.builder();

while (values.hasNext()) {

V value = values.next();

builder.put(keyFunction.apply(value), value);

}

return builder.build();

}

这样我们就可以很方便的进行转换了,如下:

List stringList = Lists.newArrayList("t1", "t2", "t3");

Map map = Maps.uniqueIndex(stringList, new Function() {

@Override

public String apply(String input) {

return input;

}

});

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

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

@Test

public void convert_list_to_map_with_java8_lambda () {

List movies = new ArrayList();

movies.add(new Movie(1, "The Shawshank Redemption"));

movies.add(new Movie(2, "The Godfather"));

Map 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())zPtgUNlT;

}

参考://jb51.net/article/104114.htm


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:如何用Java来进行文件切割和简单的内容过滤的实现
下一篇:Java基础教程之理解Annotation详细介绍
相关文章

 发表评论

暂时没有评论,来抢沙发吧~