java list转map
时间: 2023-10-13 15:29:10 浏览: 26
可以使用Java 8的Stream API来将List转换为Map。下面是一个例子:
```
List<String> list = Arrays.asList("foo", "bar", "baz");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(map);
```
这个例子中,我们使用`Arrays.asList()`方法创建了一个包含三个字符串的List。然后,我们使用`stream()`方法将List转换为Stream,使用`Collectors.toMap()`方法将Stream中的元素转换为Map,其中`Function.identity()`表示使用元素本身作为Map的键,`String::length`表示使用元素的长度作为Map的值。最后,我们使用`System.out.println()`方法输出转换后的Map。
如果List中的元素可能会重复,需要注意使用`toMap()`方法时传入的第三个参数,以避免出现重复键的情况。例如,以下代码将List中的元素转换为Map,如果出现重复键则使用后者覆盖前者:
```
List<String> list = Arrays.asList("foo", "bar", "baz", "bar");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Function.identity(), String::length, (v1, v2) -> v2));
System.out.println(map);
```
注意,这里传入的第三个参数是一个函数,它接受两个值作为参数,表示出现重复键时如何处理。在这个例子中,我们简单地使用后者覆盖前者。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)