java把List<Map<String, Object>>中每条数据的name值相同的数据计数
时间: 2024-02-03 10:09:17 浏览: 96
java计算同一个list中是否有相同的值
5星 · 资源好评率100%
可以使用Java的Stream API和Collectors工具类来实现将List<Map<String, Object>>中每条数据的name值相同的数据计数。具体步骤如下:
1. 首先,将List<Map<String, Object>>转换为Map<String, List<Map<String, Object>>>,其中键为name值,值为具有相同name值的数据列表。可以使用Stream的collect方法和Collectors.groupingBy静态方法来实现:
```java
Map<String, List<Map<String, Object>>> groupedMap = list.stream()
.collect(Collectors.groupingBy(map -> (String) map.get("name")));```
2. 然后,遍历groupedMap,计算每个name值对应的数据数量。可以使用Stream的forEach方法和Map的forEach方法来实现:
```java
groupedMap.forEach((name, dataList) -> {
int count = dataList.size();
System.out.println("Name: " + name + ", Count: " + count);
});
```
完整代码示例:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("id", 1);
map1.put("name", "dd");
map1.put("age", 23);
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("id", 2);
map2.put("name", "dd");
map2.put("age", 25);
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("id", 3);
map3.put("name", "ee");
map3.put("age", 30);
list.add(map3);
Map<String, List<Map<String, Object>>> groupedMap = list.stream()
.collect(Collectors.groupingBy(map -> (String) map.get("name")));
groupedMap.forEach((name, dataList) -> {
int count = dataList.size();
System.out.println("Name: " + name + ", Count: " + count);
});
}
}
```
输出结果:
```
Name: dd, Count: 2
Name: ee, Count: 1
```
阅读全文