最近,我和一位同事讨论了在Java中将List转换为Map的最佳方法,以及这样做是否有任何具体的好处。

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

这是一个好方法吗?

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

当前回答

这是我为这个目的写的一个小方法。它使用来自Apache Commons的Validate。

请随意使用。

/**
 * 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,你可以在一行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);
        }
    });
}};
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);

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

一个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/

根据你想要达到的目标,你会想到许多解决方案:

每个List项都是键和值

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

列表元素有一些可以查找的东西,可能是一个名称:

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

列表元素有一些可以查找的东西,并且不能保证它们是唯一的:使用google 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是从键到值的映射,而列表只是一系列元素,每个元素都有一个位置。所以它们不能自动兑换。

public class EmployeeDetailsFetchListToMap {
  public static void main(String[] args) {
    List<EmployeeDetailsFetch> list = new ArrayList<>();
    list.add(new EmployeeDetailsFetch(1L, "vinay", 25000F));
    list.add(new EmployeeDetailsFetch(2L, "kohli", 5000000F));
    list.add(new EmployeeDetailsFetch(3L, "dhoni", 20000000F));

    //adding id as key and map of id and student name
    Map<Long, Map<Long, String>> map1 = list.stream()
        .collect(
            Collectors.groupingBy(
                EmployeeDetailsFetch::getEmpId,
                Collectors.toMap(
                    EmployeeDetailsFetch::getEmpId,
                    EmployeeDetailsFetch::getEmployeeName
                )
            )
        );
    System.out.println(map1);

    //converting list into map of Student
    //Adding id as Key and Value as Student into a map
    Map<Long, EmployeeDetailsFetch> map = list.stream()
        .collect(
            Collectors.toMap(
                EmployeeDetailsFetch::getEmpId, 
                EmployeeDetailsFetch -> EmployeeDetailsFetch
            )
        );

    for(Map.Entry<Long, EmployeeDetailsFetch> m : map.entrySet()) {
      System.out.println("key :" + m.getKey() + "  Value : " + m.getValue());
    }
  }
}