美文网首页
前面讲过一次java中list去重,不过用的不是对象,这次讲Li

前面讲过一次java中list去重,不过用的不是对象,这次讲Li

作者: cmeizu | 来源:发表于2020-08-21 14:37 被阅读0次
  • 方法与之前相同.
    1. 第一种是:set,这种方法不保证顺序
    1. 第二种用lambda的distinct方法.不同点在于要重写equals方法和hashCode方法.(其根本还是用比较器)

直接上代码,看两种方法的比较.

  • 测试的自定义类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    /**
     * id
     */
    private Integer id;

    /**
     * name
     */
    private String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Student student = (Student) o;
        return Objects.equals(id, student.id) &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

方法一:

public class LinkedListDemo {
    public static void main(String[] args) {
        List<Student> list = Lists.newArrayListWithCapacity(16);
        Student student1 = new Student(1, "张三");
        Student student2 = new Student(1, "张三");
        Student student3 = new Student(3, "李四");
        Student student4 = new Student(1, "张三");
        Student student5 = new Student(2, "李四");
        Student student6 = new Student(1, "王五");
        Student student7 = new Student(1, "王二麻子");

        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);
        list.add(student7);

        Set<Student> set = new HashSet<>(list);

        set.forEach(e->System.out.println(e.getId() + "--" + e.getName()));
    }
}

结果: 是没有顺序的,但确实是去重了,但更多的时候我们需要的是不要改变顺序.

image.png

第二种方法.

public class LinkedListDemo {
    public static void main(String[] args) {
        List<Student> list = Lists.newArrayListWithCapacity(16);
        Student student1 = new Student(1, "张三");
        Student student2 = new Student(1, "张三");
        Student student3 = new Student(3, "李四");
        Student student4 = new Student(1, "张三");
        Student student5 = new Student(2, "李四");
        Student student6 = new Student(1, "王五");
        Student student7 = new Student(1, "王二麻子");

        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);
        list.add(student7);

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

        tmp.forEach(e -> System.out.println(e.getId() + "--" + e.getName()));
    }
}

结果:符合我们的预期,按照我们的给定顺序来的.

image.png

相关文章

网友评论

      本文标题:前面讲过一次java中list去重,不过用的不是对象,这次讲Li

      本文链接:https://www.haomeiwen.com/subject/kdmujktx.html