台湾佬中文网 java8 list衔接对象把柄某个属性去重
发布日期:2025-07-03 14:34 点击次数:198
图片台湾佬中文网
java8活动中list衔接去重数据,一般通过stream的distinct活动。可是distinct不够无邪,那么该若那儿置呢?
1、自界说去重函数
public static <K,T>Predicate<K> distinctPredicate(Function<K,T>function){ ConcurrentHashMap<T,Boolean> map=new ConcurrentHashMap<>(); return t->null == map.putIfAbsent(function.apply(t),true); }
2、讹诈示例
h动漫创建实体类
@AllArgsConstructor @Data class Student{ private String name; private Boolean sex; private Integer age; private Double height; private LocalDate birthday; }
创建测试数据,以名字独一去掉重叠数据。
List<Student> studentList = new ArrayList<>(); // 添加测试数据,请不要纠结数据的严谨性 studentList.add(new Student("张三", true, 18, 1.75, LocalDate.of(2005, 3, 26))); studentList.add(new Student("李四", false, 16, 1.67, LocalDate.of(2007, 8, 30))); studentList.add(new Student("王五", true, 23, 1.89, LocalDate.of(2000, 1, 16))); studentList.add(new Student("麻六", false, 27, 1.75, LocalDate.of(1996, 9, 20))); studentList.add(new Student("张三", false, 30, 1.93, LocalDate.of(1993, 6, 19))); studentList = studentList.stream().filter(distinctPredicate(Student::getName)).collect(Collectors.toList()); log.info(studentList.toString());
打印章录台湾佬中文网
[Student(name=张三, sex=true, age=18, height=1.75, birthday=2005-03-26), Student(name=李四, sex=false, age=16, height=1.67, birthday=2007-08-30), Student(name=王五, sex=true, age=23, height=1.89, birthday=2000-01-16), Student(name=麻六, sex=false, age=27, height=1.75, birthday=1996-09-20)]本站仅提供存储办事,所有本质均由用户发布,如发现存害或侵权本质,请点击举报。