不用Stream对List<Map<String,Object>>去重
时间: 2023-04-08 18:04:13 浏览: 110
可以使用Java 8中的Lambda表达式和Stream API来对List<Map<String,Object>>进行去重操作。具体实现方式如下:
List<Map<String,Object>> list = new ArrayList<>();
// 添加元素到list中
List<Map<String,Object>> distinctList = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(map -> map.get("key")))),
ArrayList::new));
这段代码使用了Collectors.toCollection()方法来创建一个TreeSet集合,该集合会根据Map中的key进行去重操作。然后使用Collectors.collectingAndThen()方法将去重后的结果转换为ArrayList类型。
需要注意的是,如果Map中的value值不同,那么这种去重方式可能会导致数据丢失。如果需要保留所有的value值,可以使用其他的去重方式,比如使用HashSet集合来进行去重操作。
相关问题
对List<Map<String,Object>>去重
可以使用Java 8的Stream API来去重,具体代码如下:
List<Map<String, Object>> list = new ArrayList<>();
// 添加数据到list中
List<Map<String, Object>> distinctList = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(m -> m.get("key")))), ArrayList::new));
// distinctList即为去重后的结果
使用stream流对List<Map<String,Object>>进行排序
可以使用Java 8的流式API和Comparator来对List<Map<String, Object>>进行排序。以下是示例代码:
```java
List<Map<String, Object>> list = new ArrayList<>();
// 添加Map数据
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "张三");
map1.put("age", 20);
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "李四");
map2.put("age", 18);
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "王五");
map3.put("age", 22);
list.add(map3);
// 按照年龄从小到大排序
List<Map<String, Object>> sortedList = list.stream()
.sorted(Comparator.comparingInt(map -> (int) map.get("age")))
.collect(Collectors.toList());
```
在代码中,我们首先创建了一个List<Map<String, Object>>,其中包含了三个Map对象。然后,我们使用stream()方法将List转换为Stream,接着使用sorted()方法和Comparator.comparingInt()方法按照年龄从小到大排序。最后,我们使用collect()方法将Stream转换为List并将结果保存在sortedList中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)