Java List去掉重复对象Java8

一、去除List中重复的String

   Set<String> set = new LinkedHashSet<>();
   set.addAll(list);
   list.clear();
   list.addAll(set);


或使用Java8的写法:

List<String> list = list.stream().distinct().collect(Collectors.toList());

二、List中对象去重

public class Student
   private Long id;
   private String name;

重写Student对象的equals()方法和hashCode()方法:

@Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;
       Student Student = (Student) o;
       if (!id.equals(Student.id)) return false;
       return name.equals(Student.name);
   }
   @Override
   public int hashCode() {
       int result = id.hashCode();
       result = 19 * result + name.hashCode();
       return result;
   }


       List<Student> students = Arrays.asList(s1, s2, s3);
       List<Student> studentsNew = new ArrayList<>();
       // 去重
       students.stream().forEach(
               s -> {
                   if (!studentsNew.contains(s)) {
                       studentsNew.add(s);
                   }
               }
           );

List的contains()方法实际上是用对象的equals方法去比较

三、根据对象的属性去重

       Set<Student> studentSet = new TreeSet<>((o1, o2) -> o1.getId().compareTo(o2.getId()));
       studentSet.addAll(students);

Java8写法

List<Student> list = Students.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Student::getId))), ArrayList::new));

使用lambda表达式的感受

lambda表达式极大的简化了代码,让整个代码的排班更加精简突显风格,但是却也增加了阅读的难度,特别是对原理不熟悉或者阅读他人代码的情况下进行调式的难度会增加。

猜你喜欢

转载自blog.csdn.net/lin252552/article/details/81128296