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

当前回答

如果没有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);
        }
    });
}};

其他回答

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

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

Apache Commons MapUtils.populateMap

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

MapUtils.populateMap

假设您有一个巴黎的列表。

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

现在需要Pair对象的Pair键的Map。

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

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