list集合根据实体类一个属性去重
时间: 2023-11-17 14:04:29 浏览: 41
可以使用 Java 8 中的 Stream API,使用 distinct() 和 lambda 表达式根据实体类的某个属性进行去重。例如:list.stream().distinct().comparator(Comparator.comparing(Entity::getProperty)).collect(Collectors.toList())。
相关问题
java中对实体类的集合根据某一列属性去重
Java中可以通过实现equals()和hashCode()方法来对实体类的集合进行去重。具体步骤如下:
1. 在实体类中重写equals()方法和hashCode()方法,其中equals()方法比较对象的某一列属性是否相等,hashCode()方法返回该列属性的hashCode值。
例如,假设有一个Student类,要根据name属性去重,可以这样实现:
```
public class Student {
private int id;
private String name;
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return Objects.equals(name, other.name);
}
public int hashCode() {
return Objects.hash(name);
}
// getter和setter方法省略
}
```
2. 使用Set集合来进行去重,因为Set集合不会存储重复的元素。可以使用HashSet或TreeSet。
例如,假设有一个List<Student>类型的集合list,可以这样去重:
```
Set<Student> set = new HashSet<>(list);
// 或者使用TreeSet
// Set<Student> set = new TreeSet<>(list);
```
这样,就可以根据name属性对Student对象进行去重了。
list实体类集合去重
以下是两种Java集合类中List实体类集合去重的例子:
1.根据多个字段去重
```java
List<ResourcesData> distinctClass = resourcesDataList.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getSkill() + ";" + o.getTechLevel()))),
ArrayList::new));
```
2.普通版
```java
projectList = projectList.stream().distinct().collect(Collectors.toList());
```
相关推荐
![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)
![](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)