stream 去除列表中某个字段去重
时间: 2023-10-09 18:16:32 浏览: 122
如何实现java8 list按照元素的某个字段去重
5星 · 资源好评率100%
回答: 要使用stream去除列表中某个字段去重,可以使用distinct()方法。首先,你需要创建一个子类,继承原始类,并重写子类的equals()方法和hashCode()方法。然后,将原始类的数据复制到子类中,并使用stream的distinct()方法对子类进行去重操作。以下是一个示例代码:\[3\]
```java
List<UserPojo> users = new ArrayList<>();
users.add(new UserPojo(1, "daji", "山东省青岛市", 19));
users.add(new UserPojo(2, "daji2", "山东省济南市", 20));
users.add(new UserPojo(3, "daji3", "北京市", 22));
users.add(new UserPojo(4, "daji", "山东省青岛市", 23));
List<OverrideEqualsPojo> overrideEqualsPojos = new ArrayList<>();
for (UserPojo user : users) {
OverrideEqualsPojo overrideEqualsPojo = new OverrideEqualsPojo();
BeanUtils.copyProperties(user, overrideEqualsPojo);
overrideEqualsPojos.add(overrideEqualsPojo);
}
overrideEqualsPojos = overrideEqualsPojos.stream().distinct().collect(Collectors.toList());
```
在上述代码中,我们创建了一个名为`OverrideEqualsPojo`的子类,重写了其`equals()`方法和`hashCode()`方法。然后,我们将原始类`UserPojo`的数据复制到子类中,并使用`stream`的`distinct()`方法对子类进行去重操作。最终,我们得到了去重后的列表`overrideEqualsPojos`。
#### 引用[.reference_title]
- *1* [Java1.8—使用Stream通过对象某个字段对集合进行去重](https://blog.csdn.net/qq_28163175/article/details/103297656)[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^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [Stream distinct 根据list某个字段去重](https://blog.csdn.net/weixin_44757863/article/details/125659749)[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^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文