最近,我和一位同事讨论了在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中,我们有收藏家的简洁解决方案:
list.stream().collect(
groupingBy(Item::getKey)
)
同时,你可以通过另一个groupingBy方法作为第二个参数来嵌套多个组:
list.stream().collect(
groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
)
这样,我们就有了多级映射,就像这样:map <key, map <key, List<Item>>>
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可能会根据这个相关的答案节省一些内存。
一个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/