Java把list转化为map集合
Java中可以使用stream和Collectors的toMap方法将List转化为Map集合。以下是一个示例代码:
import java.util.*;
import java.util.stream.Collectors;
public class ListToMapExample {
public static void main(String[] args) {
// 创建一个List
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
// 使用stream和Collectors的toMap方法将List转化为Map
Map<Integer, String> map = list.stream()
.collect(Collectors.toMap(list::indexOf, item -> item));
// 打印Map集合
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
运行以上代码,将输出以下结果:
0: Apple
1: Banana
2: Orange
在上述代码中,我们使用了stream的collect方法,并传入Collectors.toMap方法。toMap方法接受两个参数,第一个参数是用于生成Map的key的函数,这里使用了list::indexOf方法获取元素在List中的索引作为key;第二个参数是用于生成Map的value的函数,这里使用了lambda表达式item -> item保持元素不变作为value。
这样就可以将List转化为Map集合
原文地址: https://www.cveoy.top/t/topic/iDRM 著作权归作者所有。请勿转载和采集!