原文地址: Java: How to convert List to Map
文末提供源码下载.
网友 Daniel
有许多的解决方案, 这取决于你想如何实现:
每个List元素同时作为key和value
for( Object o : list ) {
map.put(o,o);
}
List元素具有某个可供查找的属性, 比如说name:
for( MyObject o : list ) {
map.put(o.name,o);
}
List元素具有某个可供查找的属性, 但又不能保证该属性是唯一的: 使用Google工具类 MultiMaps
multimap.get(key)的返回类型是集合类型
for( MyObject o : list ) {
multimap.put(o.name,o);
}
使用List元素的所在位置作为 key:
for( int i=0; i<list.size; i++ ) {
map.put(i,list.get(i));
}
...
这就要看你究竟想采用何种方式了.
如你所见, 一个Map是从一个key映射到一个value, 但是一个List则是一组元素的有序排列.所以它们不能简单的自动转换.
网友 glts
自从jdk 8以来, 使用 Collectors.toMap
的方法就成为了解决这种问题的首选.
鉴于这种任务的通用性, 我们可以把它放入静态工具类里面.
那么以后碰到这种问题,我们可以直接一行代码搞定.
/**
* Returns a map where each entry is an item of {@code list} mapped by the
* key produced by applying {@code mapper} to the item.
*
* @param list the list to map
* @param mapper the function to produce the key from a list item
* @return the resulting map
* @throws IllegalStateException on duplicate key
*/
public static <K, T> Map<K, T> toMapBy(List<T> list,
Function<? super T, ? extends K> mapper) {
return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}
最后, 如果你有一个List<Student>
类型的列表, 你可以这样转化成Map:
Map<Long, Student> studentsById = toMapBy(students, Student::getId);
网友 ripper234
正确的方法应该是使用Google的集合类
Map<String, Role> roles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
public String apply(Role from) {
return from.getName(); // or something else
}});
上述代码可优化为
Map<String, Role> roles = Maps.uniqueIndex(yourList, Role::getName());
该方法在key重复的时候会抛异常,如果要保留重复key,请用MultiMaps.index方法
ImmutableListMultimap<Integer, Student> multiMap = Multimaps.index(students, Student::getId)
multiMap.get(key)返回ImmutableList对象
Google集合类的Maven坐标
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.4-jre</version>
</dependency>
网友评论