两个List<ClientFollowUp> list 根据多个字段去重
时间: 2023-07-19 12:31:01 浏览: 48
可以使用 Java 8 的 Stream API 来实现多字段去重。假设 `ClientFollowUp` 类有两个字段 `field1` 和 `field2`,可以按照以下方式去重:
```java
List<ClientFollowUp> distinctList = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
cfu -> Arrays.asList(cfu.getField1(), cfu.getField2())))),
ArrayList::new));
```
上述代码中,使用 `Collectors.toCollection` 方法创建一个 `TreeSet` 集合,该集合可以根据多个字段去重。具体来说,`Comparator.comparing` 方法接收一个 `Function` 对象,该对象将每个 `ClientFollowUp` 对象映射为一个包含两个字段的列表,然后使用 `Arrays.asList` 方法将这个列表封装为 `List` 对象。这样,`TreeSet` 集合就可以根据这个列表进行去重。
最后,使用 `Collectors.collectingAndThen` 方法将 `TreeSet` 转换为 `ArrayList`,得到最终的去重后的列表。
相关问题
两个List<ClientFollowUp> list 根据字段 title,country,customerName 去重
如果想要根据字段 title,country,customerName 去重两个 List<ClientFollowUp>,可以使用 Java 8 的 Stream API 和 lambda 表达式结合 `distinct()` 方法和 `concat()` 方法来实现。具体实现代码如下:
```java
List<ClientFollowUp> distinctList = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
```
上述代码中的 `concat()` 方法会将两个 List 合并成一个 Stream,然后再使用 `distinct()` 方法来根据对象的 `equals()` 和 `hashCode()` 方法去重。这样就能实现对两个 List<ClientFollowUp> 根据字段 title,country,customerName 去重的操作了。
List<ClientFollowUp> list 根据字段 title,country,customerName 去重
可以使用 Java 8 的 Stream API 和 lambda 表达式来实现对 List<ClientFollowUp> list 根据字段 title,country,customerName 去重的操作,具体实现代码如下:
```java
List<ClientFollowUp> distinctList = list.stream()
.distinct()
.collect(Collectors.toList());
```
上述代码中的 `distinct()` 方法会根据对象的 `equals()` 和 `hashCode()` 方法去重,因此需要在 `ClientFollowUp` 类中重写这两个方法,例如:
```java
public class ClientFollowUp {
private String title;
private String country;
private String customerName;
// 省略构造方法和其他属性的 getter 和 setter 方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ClientFollowUp)) return false;
ClientFollowUp that = (ClientFollowUp) o;
return Objects.equals(title, that.title) &&
Objects.equals(country, that.country) &&
Objects.equals(customerName, that.customerName);
}
@Override
public int hashCode() {
return Objects.hash(title, country, customerName);
}
}
```
这样就能实现对 List<ClientFollowUp> list 根据字段 title,country,customerName 去重的操作了。