stream中用list转map
时间: 2023-11-10 09:03:49 浏览: 43
可以使用Java 8中的Stream API中的Collectors.toMap()方法将一个List转换为Map。示例代码如下:
```
List<String> list = Arrays.asList("apple", "banana", "orange");
Map<String, Integer> map = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
```
上述代码将List中的每个元素作为Map的key,将每个元素的长度作为Map的value。
相关问题
list转map(string,object)
可以使用Java Stream API来将List转换为Map<String,Object>,代码如下:
```java
List<MyObject> list = new ArrayList<>();
Map<String, Object> map = list.stream().collect(Collectors.toMap(MyObject::getKey, MyObject::getValue));
```
其中,MyObject为List中元素的类型,getKey()和getValue()是获取MyObject中用作key和value的方法。可以按实际情况进行修改。
java中list转化为map
在Java中,可以通过以下代码将List转换为Map:
```
List<MyObject> list = ...;
Map<KeyType, MyObject> map = list.stream()
.collect(Collectors.toMap(MyObject::getKey, Function.identity()));
```
其中,MyObject是List中的元素类型,KeyType是MyObject中用作Map键的属性类型。getKey是MyObject类中的方法,用于返回Map键值。Function.identity()返回一个函数,它将输入对象作为输出返回。
如果MyObject中的属性不能作为Map键,也可以使用lambda表达式指定键值:
```
Map<KeyType, MyObject> map = list.stream()
.collect(Collectors.toMap(
obj -> obj.getKey(),
Function.identity()
));
```
注意,如果List中有重复的键值,上述代码会抛出IllegalStateException异常。可以在toMap方法中传递一个合并函数来处理重复键值:
```
Map<KeyType, MyObject> map = list.stream()
.collect(Collectors.toMap(
MyObject::getKey,
Function.identity(),
(oldValue, newValue) -> oldValue
));
```
这里传递了一个合并函数,它将旧值保留为Map的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)