两个List<ClientFollowUp> list 根据字段 title,country,customerName 去重
时间: 2023-07-18 21:32:24 浏览: 42
如果想要根据字段 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 去重的操作了。
List<ClientFollowUp> distinctList = Stream.concat(list.stream(), result.stream()) .distinct() .collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing( p -> Arrays.asList(p.getCustomerName())))), ArrayList::new));
这段代码的作用是将两个 List 合并,并去重,去重的方式是按照 ClientFollowUp 对象的 customerName 属性进行比较。
具体来说,这段代码使用了 Java 8 中的 Stream API,首先通过 `Stream.concat(list.stream(), result.stream())` 将两个 List 进行合并,得到一个 Stream 对象。然后调用 `distinct()` 方法对 Stream 中的元素进行去重操作,由于 ClientFollowUp 对象没有实现 Comparable 接口,因此需要在创建 TreeSet 对象时指定 Comparator 对象进行比较。这里使用了 Lambda 表达式 `Comparator.comparing(p -> Arrays.asList(p.getCustomerName()))` 创建了一个 Comparator 对象,表示按照 ClientFollowUp 对象的 customerName 属性进行比较。最后,使用 `collect(Collectors.collectingAndThen(...))` 方法将去重后的元素收集到一个 ArrayList 中,并返回该 List。
需要注意的是,这种方式只能对 List 中的元素进行浅层去重,即只能去除对象的引用相同的元素,如果需要对 List 中的元素进行深层去重,需要在 ClientFollowUp 类中重写 equals 和 hashCode 方法。