1、根据对象去重
根据对象中的某个字段去重
import com.top.test.dto.Student; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; public class ListStreamDistinctTest { public static void main(String[] args) { // 一个集合中放入4个学生对象 List<Student> list = new ArrayList<>(); list.add(new Student(10002L, "ZhangSan", 18, 175.2)); list.add(new Student(10001L, "LiSi", 19, 175.2)); list.add(new Student(10004L, "Peter", 19, 170.8)); list.add(new Student(10004L, "Peter", 19, 170.8)); // 按整个个对象去重 System.out.println("整个对象去重:"); list.stream().distinct() .forEach(System.out::println); // 指定某个字段去重 System.out.println("指定age属性去重(方法一):"); list.stream().filter(distinctByKey1(s -> s.getAge())) .forEach(System.out::println); // 方法二(用循环) System.out.println("指定age属性去重(方法二):"); TreeSet<Student> students = new TreeSet<>(Comparator.comparing(s -> s.getAge())); for (Student student : list) { students.add(student); } new ArrayList<>(students) .forEach(System.out::println); // 方法三: System.out.println("指定age属性去重(方法三):"); list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getAge()))), ArrayList::new)) .forEach(System.out::println); } // 次方法 static <T> Predicate<T> distinctByKey1(Function<? super T, ?> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } }
2、执行结果
整个对象去重: Student{id=10002, name='ZhangSan', age=18, height=175.2} Student{id=10001, name='LiSi', age=19, height=175.2} Student{id=10004, name='Peter', age=19, height=170.8} 指定age属性去重(方法一): Student{id=10002, name='ZhangSan', age=18, height=175.2} Student{id=10001, name='LiSi', age=19, height=175.2} 指定age属性去重(方法二): Student{id=10002, name='ZhangSan', age=18, height=175.2} Student{id=10001, name='LiSi', age=19, height=175.2} 指定age属性去重(方法三): Student{id=10002, name='ZhangSan', age=18, height=175.2} Student{id=10001, name='LiSi', age=19, height=175.2}
3、使用比较方法针对对象中的某个字段去重
ArrayList<ProductProcessDrawbackDto> collect = records1.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator.comparing( ProductProcessDrawbackDto::getId))), ArrayList::new));
4、使用比较方法根据对象中的多个字段去重
ArrayList<PatentDto> collect1 = patentDtoList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new)
https://www.cnblogs.com/better-farther-world2099/articles/16926282.html