java list 根据字段去重
时间: 2024-08-16 18:03:08 浏览: 31
在Java中,如果你有一个List并想要根据其中的对象的某个字段进行去重,可以创建一个新的Map(因为HashMap不允许重复键),利用这个字段作为键来进行去重。以下是基本步骤:
```java
import java.util.*;
List<YourClass> list = ...; // 你的List对象
// 假设你要基于名为"fieldToUniqify"的字段去重
Set<String> uniqueValues = new HashSet<>(); // 使用HashSet防止重复
list.forEach(item -> {
String fieldValue = item.getFieldToUniqify();
if (!uniqueValues.contains(fieldValue)) { // 如果字段值不在集合中
uniqueValues.add(fieldValue); // 添加到集合
// 或者你可以直接在这里创建新的list添加不重复的项
yourNewList.add(item);
}
});
```
在这个例子中,`yourNewList`将只包含`fieldToUniqify`字段不重复的元素。
相关问题
java list根据字段去重
可以使用Java 8的Lambda表达式和Stream API来根据字段去重一个List。以下是一个示例代码:
```java
List<Employee> employees = Arrays.asList(
new Employee("Alice", 25),
new Employee("Bob", 26),
new Employee("Alice", 25),
new Employee("Charlie", 27),
new Employee("Bob", 26)
);
List<Employee> distinctEmployees = employees.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctEmployees);
```
其中,Employee类的定义如下:
```java
public class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Employee)) return false;
Employee other = (Employee) obj;
return name.equals(other.name) && age == other.age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
```
在上面的代码中,我们先创建了一个包含重复元素的List。然后,我们使用distinct()方法去重,并使用collect(Collectors.toList())方法将结果收集到一个新的List中。注意,我们需要在Employee类中实现equals()和hashCode()方法来进行去重。
java8 list根据字段去重
Java8中可以使用stream的distinct方法或者filter方法来实现List按照元素的某个字段去重。其中,distinct方法需要重写对象的equals和hashCode方法,以该字段来判断比较是否相同;而filter方法则需要在外面创建一个HashMap,以该字段为key,判断是否已经存在该元素,若不存在则加入到结果集中。具体实现可以参考以下两个引用:
1.重写Info类的equals和hashCode方法,以recordNum来判断比较是否相同,然后用stream的distinct方法来去重
```
public class Info extends BaseEntity {
...
private String recordNum;
...
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Info info = (Info) o;
return Objects.equals(recordNum, info.recordNum);
}
}
//去重
List<Info> distinctInfos= infos.stream().distinct().collect(Collectors.toList());
```
2.通过stream的filter方法来去重,不定义去重方法,在外面创建HashMap
```
Map<Object, Boolean>