list 按照元素的某个字段去重
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer age;
private String name;
}
测试数据
ListstudentList = Lists.newArrayList(); studentList.add(new Student(28, "river")); studentList.add(new Student(12, "lucy")); studentList.add(new Student(33, "frank")); studentList.add(new Student(33, "lucy"));
java8 通过tree set 去重
ListstudentDistinctList = studentList.stream() .collect(Collectors.collectingAndThen (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> t.getName()))), ArrayList::new ) ); System.out.println(new Gson().toJson(studentDistinctList));
扩展distinct 方法去重
ListstudentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName())) .collect(Collectors.toList()); System.out.println(new Gson().toJson(studentDistinct2List));
工具类
public class StreamUtil {
public static Predicate distinctByKey(Function super T, ?> keyExtractor) {
Set
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



