263

最近,我与一位同事讨论了转换ListMapJava 的最佳方式以及这样做是否有任何特定的好处。

我想知道最佳转换方法,如果有人能指导我,我将不胜感激。

这是好方法吗:

List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
    resultsMap.put((Integer) o[0], (String) o[1]);
}
4

18 回答 18

384

使用和类在一行中完成此操作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 值,计算它的模 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)

希望能帮助到你!:)

于 2014-01-02T16:58:21.637 回答
211
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);

当然,假设每个 Item 都有一个getKey()返回正确类型的键的方法。

于 2010-11-09T20:45:06.210 回答
115

万一这个问题没有因为重复而关闭,正确的答案是使用 Google Collections

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
  public String apply(Role from) {
    return from.getName(); // or something else
  }});
于 2011-12-15T09:32:44.940 回答
35

短而甜。

使用 Java 8,您可以执行以下操作:

Map<Key, Value> result= results
                       .stream()
                       .collect(Collectors.toMap(Value::getName,Function.identity()));

Value可以是您使用的任何对象。

于 2018-03-01T19:56:50.343 回答
17

从 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()));
}

以下是您在 a 上使用它的方法List<Student>

Map<Long, Student> studentsById = toMapBy(students, Student::getId);
于 2014-10-27T18:40:39.390 回答
15

Alexis 已经使用方法在Java 8toMap(keyMapper, valueMapper)中发布了一个答案。根据此方法实现的文档:

不保证返回的 Map 的类型、可变性、可序列化性或线程安全性。

因此,如果我们对接口的特定实现感兴趣,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()or都可以,但根据这个相关的答案i->i,它似乎可能Function.identity()i -> i节省一些内存。

于 2017-12-10T07:22:17.730 回答
10

AListMap在概念上是不同的。AList是项目的有序集合。项目可以包含重复项,并且项目可能没有任何唯一标识符(键)的概念。AMap具有映射到键的值。每个键只能指向一个值。

因此,根据您List的项目,可能会也可能不会将其转换为Map. 您List的商品没有重复项吗?每个项目都有唯一的密钥吗?如果是这样,那么可以将它们放在Map.

于 2010-11-09T20:52:57.743 回答
8

还有一种使用Google 库中的Maps.uniqueIndex(...)的简单方法

于 2012-04-02T22:17:31.860 回答
5

通用方法

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);
}
于 2011-11-23T23:10:48.303 回答
5

使用 java-8 流

Map<Integer, String> map = results.stream().collect(Collectors.toMap(e -> ((Integer) e[0]), e -> (String) e[1]));
于 2020-01-18T12:09:16.273 回答
4

如果没有 java-8,您将能够在一行 Commons 集合和 Closure 类中执行此操作

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);
        }
    });
}};
于 2015-05-15T15:00:25.047 回答
3

就像已经说过的,在 java-8 中,我们有 Collectors 的简洁解决方案:

  list.stream().collect(
         groupingBy(Item::getKey)
        )

而且,您可以嵌套多个组,将另一个 groupingBy 方法作为第二个参数传递:

  list.stream().collect(
         groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
        )

这样,我们将拥有多级地图,如下所示:Map<key, Map<key, List<Item>>>

于 2019-01-14T16:21:40.507 回答
2

许多解决方案浮现在脑海中,具体取决于您想要实现的目标:

每个列表项都是键和值

for( Object o : list ) {
    map.put(o,o);
}

列表元素有一些东西可以查找它们,也许是一个名字:

for( MyObject o : list ) {
    map.put(o.name,o);
}

列表元素有一些东西可以查找它们,并且不能保证它们是唯一的:使用 Googles MultiMaps

for( MyObject o : list ) {
    multimap.put(o.name,o);
}

将所有元素的位置作为键:

for( int i=0; i<list.size; i++ ) {
    map.put(i,list.get(i));
}

...

这真的取决于你想要达到什么。

从示例中可以看出,Map 是从键到值的映射,而列表只是一系列元素,每个元素都有一个位置。所以它们根本不能自动转换。

于 2010-11-09T20:49:46.140 回答
2

这是我为此目的而编写的一个小方法。它使用来自 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;
}
于 2011-07-14T14:00:02.100 回答
2

将 a List<?>of objects转换为 a 的 Java 8 示例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/

于 2017-05-25T09:50:07.587 回答
2

您可以利用 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/

于 2017-06-09T04:33:48.007 回答
0

我喜欢 Kango_V 的回答,但我认为它太复杂了。我认为这更简单——也许太简单了。如果愿意,您可以将 String 替换为 Generic 标记,并使其适用于任何 Key 类型。

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();
                    }
                } );
于 2011-09-20T15:42:39.637 回答
0

Apache Commons MapUtils.populateMap

如果您不使用 Java 8 并且出于某种原因不想使用显式循环,请尝试MapUtils.populateMap使用 Apache Commons。

MapUtils.populateMap

假设您有一个Pairs 列表。

List<ImmutablePair<String, String>> pairs = ImmutableList.of(
    new ImmutablePair<>("A", "aaa"),
    new ImmutablePair<>("B", "bbb")
);

你现在想要一个对象Pair的键的 Map 。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);
于 2018-03-27T02:46:25.720 回答