使用stream流 将list 转为map,key相等时 取出前者的值加上后者的值 赋值给新的值
时间: 2023-05-19 12:03:00 浏览: 51
可以使用Java 8的Stream API来实现这个功能,代码如下:
```
List<String> list = Arrays.asList("a", "b", "c", "a", "d", "b");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Function.identity(), s -> 1, Integer::sum));
System.out.println(map);
```
这段代码将一个字符串列表转换为一个字符串到整数的映射,其中字符串的值是列表中的元素,整数的值是该元素在列表中出现的次数。如果有多个元素具有相同的字符串值,则将它们的计数相加。最终的输出将是:
```
{a=2, b=2, c=1, d=1}
```
这个映射将每个字符串映射到它在列表中出现的总次数。
相关问题
使用stream流 将list 转为map,key相等时 value 累加
可以使用Java 8中的stream流来将list转为map,并且在key相等时将value累加。具体代码如下:
```
List<String> list = Arrays.asList("apple", "banana", "orange", "apple", "orange");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));
System.out.println(map);
```
输出结果为:{orange=2, banana=1, apple=2}
这段代码将list中的元素作为key,初始值为1作为value,使用Integer::sum函数将相同key的value值累加。
stream流list转map重复key 取最大值
可以使用Java 8的Stream API,先将List转换为Map,然后使用merge方法解决重复key的问题,取最大值。示例代码如下:
```java
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Item> itemList = Arrays.asList(
new Item("key1", 10),
new Item("key2", 20),
new Item("key3", 30),
new Item("key1", 5),
new Item("key2", 15)
);
Map<String, Integer> resultMap = itemList.stream()
.collect(Collectors.toMap(
Item::getKey, // key映射函数
Item::getValue, // value映射函数
Integer::max // 解决重复key的方法,取最大值
));
System.out.println(resultMap); // 输出:{key1=10, key2=20, key3=30}
}
static class Item {
private String key;
private int value;
public Item(String key, int value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public int getValue() {
return value;
}
}
}
```