stream去重map
时间: 2023-09-05 07:08:23 浏览: 122
Java中对List去重 Stream去重的解决方法
根据提供的引用内容,使用stream去重map的方法如下所示:
首先,创建一个List来存储Map对象:
```
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("id", "id1");
map.put("name", "name1");
map.put("age", "22");
list.add(new HashMap<>(map));
map.put("id", "id1");
map.put("name", "name1");
map.put("age", "22");
list.add(new HashMap<>(map));
map.put("id", "id1");
map.put("name", "name2");
map.put("age", "22");
list.add(new HashMap<>(map));
map.put("id", "id2");
map.put("name", "name2");
map.put("age", "32");
list.add(new HashMap<>(map));
```
然后,使用stream和collect方法结合起来,使用Collectors.collectingAndThen方法和TreeSet来去除重复的map对象,通过对比id和name字段来判断两个map是否相等:
```
list = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing((o) -> o.get("id") + ";" + o.get("name")))),
ArrayList::new));
```
这样,list中的map对象就会被去重,只保留一个拥有相同id和name字段的map对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Java--Stream的两个小用法(去重+map排序)](https://blog.csdn.net/GuessBUG/article/details/96109069)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [使用Stream流对List中的Map进行多条件去重](https://blog.csdn.net/wounler/article/details/121522761)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文