最近,我和一位同事讨论了在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]);
}

当前回答

还有一种简单的方法,使用谷歌番石榴库中的Maps.uniqueIndex(…)

其他回答

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

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

同时,你可以通过另一个groupingBy方法作为第二个参数来嵌套多个组:

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

这样,我们就有了多级映射,就像这样:map <key, map <key, List<Item>>>

又短又甜。

使用Java 8,你可以做到以下几点:

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

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

普遍的方法

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流

Map<Integer, String> map = results.stream().collect(Collectors.toMap(e -> ((Integer) e[0]), e -> (String) e[1]));
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);

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