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

当前回答

Alexis已经在Java 8中使用toMap方法(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()或i->i都可以,但似乎Function.identity()而不是i->i可能会根据这个相关的答案节省一些内存。

其他回答

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

每个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是从键到值的映射,而列表只是一系列元素,每个元素都有一个位置。所以它们不能自动兑换。

又短又甜。

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

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

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

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

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

使用java-8流

Map<Integer, String> map = results.stream().collect(Collectors.toMap(e -> ((Integer) e[0]), e -> (String) e[1]));

Alexis已经在Java 8中使用toMap方法(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()或i->i都可以,但似乎Function.identity()而不是i->i可能会根据这个相关的答案节省一些内存。