Java:如何将列表转换为地图
-
30-09-2019 - |
题
最近,我与一位同事交谈,讨论将是转换的最佳方式 List
到 Map
在Java,如果有任何特定的好处。
我想知道最佳的转换方法,如果有人可以指导我,真的很感激。
这是好方法:
List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
resultsMap.put((Integer) o[0], (String) o[1]);
}
解决方案
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);
假设每个项目都有一个 getKey()
返回适当类型的键的方法。
其他提示
和 Java-8, ,您可以使用 流, ,和 Collectors
班级。
Map<String, Item> map =
list.stream().collect(Collectors.toMap(Item::getKey, item -> item));
简短演示:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test{
public static void main (String [] args){
List<Item> list = IntStream.rangeClosed(1, 4)
.mapToObj(Item::new)
.collect(Collectors.toList()); //[Item [i=1], Item [i=2], Item [i=3], Item [i=4]]
Map<String, Item> map =
list.stream().collect(Collectors.toMap(Item::getKey, item -> item));
map.forEach((k, v) -> System.out.println(k + " => " + v));
}
}
class Item {
private final int i;
public Item(int i){
this.i = i;
}
public String getKey(){
return "Key-"+i;
}
@Override
public String toString() {
return "Item [i=" + i + "]";
}
}
输出:
Key-1 => Item [i=1]
Key-2 => Item [i=2]
Key-3 => Item [i=3]
Key-4 => Item [i=4]
如评论中所述,您可以使用 Function.identity()
代替 item -> item
, ,尽管我发现 i -> i
相当明确。
请注意,如果您的功能不是二进制运算符,则可以使用二进制操作员。例如,让我们考虑一下 List
以及用于INT值的映射函数,计算IT的结果模拟3:
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<String, Integer> map =
intList.stream().collect(toMap(i -> String.valueOf(i % 3), i -> i));
运行此代码时,您会发现一个错误说 java.lang.IllegalStateException: Duplicate key 1
. 。这是因为1%3与4%3相同,因此,给定键映射函数具有相同的密钥值。在这种情况下,您可以提供合并操作员。
这是一个概括值的人; (i1, i2) -> i1 + i2;
可以用方法参考替换 Integer::sum
.
Map<String, Integer> map =
intList.stream().collect(toMap(i -> String.valueOf(i % 3),
i -> i,
Integer::sum));
现在输出:
0 => 9 (i.e 3 + 6)
1 => 5 (i.e 1 + 4)
2 => 7 (i.e 2 + 5)
希望能帮助到你! :)
以防万一这个问题没有以重复的方式关闭, 正确的答案是使用Google系列:
Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
public String apply(Role from) {
return from.getName(); // or something else
}});
自Java 8以来 @zouzou的回答 使用 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<Long, Student> studentsById = toMapBy(students, Student::getId);
使用Java 8,您可以执行以下操作:
Map<Key, Value> result= results
.stream()
.collect(Collectors.toMap(Value::getName,Function.identity()));
Value
可以是您使用的任何对象。
一种 List
和 Map
在概念上是不同的。一种 List
是有序的项目集合。这些项目可以包含重复项,并且项目可能没有任何唯一标识符(键)的概念。一种 Map
具有映射到键的值。每个键只能指向一个值。
因此,取决于您 List
的项目,它可能无法转换为也可能无法转换为 Map
. 。请问您 List
的项目没有重复?每个项目都有唯一的钥匙吗?如果是这样,则可以将它们放在 Map
.
也有一种简单的方法 MAPS.UniqueIndex(...) 来自Google 瓜瓦 库
亚历克西斯已经在 Java 8 使用方法 toMap(keyMapper, valueMapper)
. 。按照 Doc 对于此方法实施:
返回的地图的类型,可突出性,序列化或线程安全性都无法保证。
因此,如果我们对特定的实施感兴趣 Map
接口,例如 HashMap
然后,我们可以使用超载表单为:
Map<String, Item> map2 =
itemList.stream().collect(Collectors.toMap(Item::getKey, //key for map
Function.identity(), // value for map
(o,n) -> o, // merge function in case of conflict with keys
HashMap::new)); // map factory - we want HashMap and not any Map implementation
虽然使用 Function.identity()
或者 i->i
很好,但似乎 Function.identity()
代替 i -> i
可能会节省一些记忆 回答.
通用方法
public static <K, V> Map<K, V> listAsMap(Collection<V> sourceList, ListToMapConverter<K, V> converter) {
Map<K, V> newMap = new HashMap<K, V>();
for (V item : sourceList) {
newMap.put( converter.getKey(item), item );
}
return newMap;
}
public static interface ListToMapConverter<K, V> {
public K getKey(V item);
}
没有Java-8,您将可以在一行Commons集合和关闭类中进行此操作
List<Item> list;
@SuppressWarnings("unchecked")
Map<Key, Item> map = new HashMap<Key, Item>>(){{
CollectionUtils.forAllDo(list, new Closure() {
@Override
public void execute(Object input) {
Item item = (Item) input;
put(i.getKey(), item);
}
});
}};
我想到了许多解决方案,具体取决于您想实现的目标:
每个列表项目都是钥匙和值
for( Object o : list ) {
map.put(o,o);
}
列表元素可以查找它们,也许是一个名字:
for( MyObject o : list ) {
map.put(o.name,o);
}
列表元素可以查找它们,并且不能保证它们是唯一的:使用Google 多图
for( MyObject o : list ) {
multimap.put(o.name,o);
}
将所有要素作为关键的立场:
for( int i=0; i<list.size; i++ ) {
map.put(i,list.get(i));
}
...
这确实取决于您想实现的目标。
从示例中可以看到,地图是从钥匙到值的映射,而列表只是一系列具有位置的元素。因此,它们根本不是自动转换的。
这是我为此目的编写的一些方法。它使用来自Apache Commons的验证。
随意使用它。
/**
* Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
* the value of the key to be used and the object itself from the list entry is used as the
* objct. An empty <code>Map</code> is returned upon null input.
* Reflection is used to retrieve the key from the object instance and method name passed in.
*
* @param <K> The type of the key to be used in the map
* @param <V> The type of value to be used in the map and the type of the elements in the
* collection
* @param coll The collection to be converted.
* @param keyType The class of key
* @param valueType The class of the value
* @param keyMethodName The method name to call on each instance in the collection to retrieve
* the key
* @return A map of key to value instances
* @throws IllegalArgumentException if any of the other paremeters are invalid.
*/
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
final Class<K> keyType,
final Class<V> valueType,
final String keyMethodName) {
final HashMap<K, V> map = new HashMap<K, V>();
Method method = null;
if (isEmpty(coll)) return map;
notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));
try {
// return the Method to invoke to get the key for the map
method = valueType.getMethod(keyMethodName);
}
catch (final NoSuchMethodException e) {
final String message =
String.format(
Messages.getString(METHOD_NOT_FOUND),
keyMethodName,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
try {
for (final V value : coll) {
Object object;
object = method.invoke(value);
@SuppressWarnings("unchecked")
final K key = (K) object;
map.put(key, value);
}
}
catch (final Exception e) {
final String message =
String.format(
Messages.getString(METHOD_CALL_FAILED),
method,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
return map;
}
您可以利用Java 8的流API。
public class ListToMap {
public static void main(String[] args) {
List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));
Map<String, User> map = createHashMap(items);
for(String key : map.keySet()) {
System.out.println(key +" : "+map.get(key));
}
}
public static Map<String, User> createHashMap(List<User> items) {
Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return map;
}
}
有关更多详细信息,请访问: http://codecramp.com/java-8-streams-api-convert-list-map/
就像已经说过的那样,在Java-8中,我们有收藏家的简洁解决方案:
list.stream().collect(
groupingBy(Item::getKey)
)
而且,您可以嵌套多组将其他分组方法作为第二个参数:
list.stream().collect(
groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
)
这样,我们将拥有多个级别的地图,因此: Map<key, Map<key, List<Item>>>
Java 8示例转换 List<?>
对象 Map<k, v>
:
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", new Date()));
list.add(new Hosting(2, "linode.com", new Date()));
list.add(new Hosting(3, "digitalocean.com", new Date()));
//example 1
Map<Integer, String> result1 = list.stream().collect(
Collectors.toMap(Hosting::getId, Hosting::getName));
System.out.println("Result 1 : " + result1);
//example 2
Map<Integer, String> result2 = list.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));
复制的代码从:
https://www.mkyong.com/java8/java-8-convert-list-to-map/
我喜欢kango_v的答案,但我认为这太复杂了。我认为这更简单 - 也许太简单了。如果倾斜,则可以用通用标记替换字符串,并使其适用于任何关键类型。
public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
Map<String, E> newMap = new HashMap<String, E>();
for( E item : sourceList ) {
newMap.put( converterInterface.getKeyForItem( item ), item );
}
return newMap;
}
public interface ListToMapConverterInterface<E> {
public String getKeyForItem(E item);
}
这样使用:
Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
new ListToMapConverterInterface<PricingPlanAttribute>() {
@Override
public String getKeyForItem(PricingPlanAttribute item) {
return item.getFullName();
}
} );
Apache Commons maputils.populatemap
如果您不使用Java 8,并且由于某种原因不想使用明确的循环,请尝试 MapUtils.populateMap
来自Apache Commons。
说你有一个清单 Pair
s。
List<ImmutablePair<String, String>> pairs = ImmutableList.of(
new ImmutablePair<>("A", "aaa"),
new ImmutablePair<>("B", "bbb")
);
现在您想要一张地图 Pair
的关键 Pair
目的。
Map<String, Pair<String, String>> map = new HashMap<>();
MapUtils.populateMap(map, pairs, new Transformer<Pair<String, String>, String>() {
@Override
public String transform(Pair<String, String> input) {
return input.getKey();
}
});
System.out.println(map);
给出输出:
{A=(A,aaa), B=(B,bbb)}
话虽如此,一个 for
循环可能更容易理解。 (下面给出相同的输出):
Map<String, Pair<String, String>> map = new HashMap<>();
for (Pair<String, String> pair : pairs) {
map.put(pair.getKey(), pair);
}
System.out.println(map);