根据bean对象的某几个属性去重
distinct是根据bean的hash与equals方法去重,达不到本次需求的要求
@Data
public class Dish {
private String name; //菜的名称
private Boolean vegetaian; //是否为素
private Integer calories; //卡路里
private Type type; //类型(肉 鱼 其他)
public Dish() {
}
public Dish(String name, Boolean vegetaian, Integer calories, Type type) {
this.name = name;
this.vegetaian = vegetaian;
this.calories = calories;
this.type = type;
}
public enum Type {MEAT, FISH, OTHER} //肉 鱼 其他
}
public class DishList {
//数据准备
public static List getDish1List() {
return Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("beef", false, 701, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)
);
}
}
/**
* 根据type-name去重的Function
*
* @return
*/
public static Function distinctByKeyFunction() {
return (Dish dish) -> dish.getType() + "-" + dish.getName();
}
@Test
public void distinctByKey1() {
List dish1List = DishList.getDish1List();
List distinctDishList = dish1List.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(distinctByKeyFunction()))), ArrayList::new));
System.out.println(distinctDishList);
}
先将list转成TreeSet(TreeSet含有比较器)过滤重复数据,再将转换为 ArrayList
collectingAndThen的使用链接
方法:
public static Predicate distinctByKey(Function super T, ?> function) {
Map
测试:
@Test
public void distinctByKey2() {
List dish1List = DishList.getDish1List();
List distinctDishList = dish1List.stream().filter(distinctByKey(distinctByKeyFunction())).collect(Collectors.toList());
System.out.println(distinctDishList);
}
public static Predicate distinctByKeyOriginal() {
Map
String key = dish.getType() + “” + dish.getName(); 将其摘出,使用Function自由组合,就成了 “function.apply(t)”。
t -> seen.putIfAbsent(function.apply(t), Boolean.TRUE) == null;使用匿名内部类形式替换
两个 list<bean> 使用java8根据某几个属性去重复
方案二学习链接