Java List去掉重复对象

两个list去重,

如果list里面都是基础对象的话,直接去重就好了

list1.removeAll(list2);

list2.addAll(list1);

但是如果list里面是对象的话,我们就要考虑重写list比较的方法了,list用的是equals,思路如下:


Person类

public class Person {
    private Long id;

    private String name;

    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

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

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (!id.equals(person.id)) return false;
        return name.equals(person.name);

    }

    @Override
    public int hashCode() {
        int result = id.hashCode();
        result = 31 * result + name.hashCode();
        return result;
    }

下面对象去重的代码:

Person p1 = new Person(1l, "jack");
        Person p2 = new Person(3l, "jack chou");
        Person p3 = new Person(2l, "tom");
        Person p4 = new Person(4l, "hanson");
        Person p5 = new Person(5l, "胶布虫");

        List persons = Arrays.asList(p1, p2, p3, p4, p5, p5, p1, p2, p2);

        List personList = new ArrayList<>();
        // 去重
        persons.stream().forEach(
                p -> {
                    if (!personList.contains(p)) {
                        personList.add(p);
                    }
                }
        );
        System.out.println(personList);

List 的contains()方法底层实现使用对象的equals方法去比较的,其实重写equals()就好,但重写了equals最好将hashCode也重写了。

可以参见:http://stackoverflow.com/questions/30745048/how-to-remove-duplicate-objects-from-java-arraylist 
http://blog.csdn.net/growing_tree/article/details/46622579


 
  

 
  


你可能感兴趣的:(Java List去掉重复对象)