public class ListSelect {
public static void main(String[] args) {
List<Car> carList1 = new ArrayList();
carList1.add(new Car("1", "张三", "蓝色", "hello", 15));
carList1.add(new Car("1", "李四", "蓝色", "hello1", 16));
carList1.add(new Car("1", "王五", "绿色", "hello2", 17));
carList1.add(new Car("1", "王五", "绿色", "hello3", 18));
List<Car> carList2 = new ArrayList();
List<Car> collect = carList1.stream().filter(distinctByKey(Car::getModel)).collect(Collectors.toList());
carList2.addAll(collect);
System.out.println("collect = " + collect);
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
@Data
public class Car {
private String id;
private String model;//型号
private String color;//颜色
private String volume;//排量
private int year;//年份
private Tires tires;//轮胎
public Car() {
}
public Car(String id, String model, String color, String volume, int year) {
this.id = id;
this.model = model;
this.color = color;
this.volume = volume;
this.year = year;
}
}
结果如下: