java8 stream 根据map某个属性 对 map的list 去重
时间: 2023-11-17 10:10:16 浏览: 54
可以使用Java 8的Stream API来实现根据map某个属性对map的list去重。具体做法如下:
1. 定义一个Map对象的List,假设它被称为mapList。
2. 使用Stream API将mapList转换为一个新的Stream对象。
3. 使用Stream的distinct()方法去重。
4. 使用Stream的collect()方法将去重后的结果转换为List。
例如,假设我们有以下Map对象的List:
```
List<Map<String, Object>> mapList = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("id", 1);
map1.put("name", "John");
Map<String, Object> map2 = new HashMap<>();
map2.put("id", 2);
map2.put("name", "Jane");
Map<String, Object> map3 = new HashMap<>();
map3.put("id", 1);
map3.put("name", "James");
mapList.add(map1);
mapList.add(map2);
mapList.add(map3);
```
我们想根据"id"属性对mapList进行去重,可以使用以下代码:
```
List<Map<String, Object>> distinctMapList = mapList.stream()
.filter(distinctByKey(map -> map.get("id")))
.collect(Collectors.toList());
```
其中,distinctByKey()方法的实现如下:
```
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
```
该方法使用ConcurrentHashMap来保存已经出现过的key,实现了根据map某个属性去重的功能。