@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserCar {
private Integer id;
private String carNo;
public static void main(String[] args) {
List<UserCar> cars = new ArrayList<>();
cars.add(UserCar.builder().id(1).carNo("AA").build());
cars.add(UserCar.builder().id(2).carNo("AA").build());
cars.add(UserCar.builder().id(2).carNo("AA").build());
cars.add(UserCar.builder().id(3).carNo("AB").build());
List<UserCar> carList = removeDuplicates4(cars);
System.out.println(JSONObject.toJSONString(carList));
}
}
12345678910111213141516171819
private static List<UserCar> removeDuplicates(List<UserCar> userCars) {
Set<UserCar> personSet = new TreeSet<UserCar>(Comparator.comparing(UserCar::getCarNo));
personSet.addAll(userCars);
return new ArrayList<UserCar>(personSet);
}
1234567
这也是大多数人第一想到的,借助 TreeSet 去重,其中 TreeSet 的其中一个构造函数接收一个排序的算法,同时这也会用到 TreeSet 的去重策略上.
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
12345
private static List<UserCar> removeDuplicates2(List<UserCar> cars) {
return cars.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<UserCar>(Comparator.comparing(UserCar::getCarNo))), ArrayList::new)
);
}
12345
private static List<UserCar> removeDuplicates3(List<UserCar> cars) {
// 用于临时存放id
List<String> filterCars = new ArrayList<>();
return cars.stream().filter(
e -> {
boolean found = !filterCars.contains(e.getCarNo());
filterCars.add(e.getCarNo());
return found;
}
).collect(Collectors.toList());
}
12345678910111213
/**
* 使用hutool工具类
* @param cars
* @return
*/
private static List<UserCar> removeDuplicates5(List<UserCar> cars) {
return CollUtil.distinct(cars, UserCar::getCarNo, true);
}
123456789