今天遇到一个问题,一个List<entity> 里面的数据是有重复的,需要去掉重复。如果for 和for 效率太差,想康康有么有大佬写的牛P的。
结果CSDN一搜,10个里9个都是一样的,互相抄来抄去的。由于项目版本以及一些其他原因,其他博客的办法无法解决我的需求。就
只有自己上手了。
首先说下思路:
- 假如我的List数据是这样的,他的Id是唯一不会重复,但是name和code任意一项会重复,并且可能两个都重复,我们要去掉重复的数据
首先看我们的entity
package com.example.hashmap.learnhasnmap.per;
public class Student {
private int id;
private String name;
private String code;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Student(int id, String name, String code) {
this.id = id;
this.name = name;
this.code = code;
}
//重写equals方法
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name != other.name)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
再看我们的处理方法
//创建集合
ArrayList<Student> list = new ArrayList<Student>();
//创建集合元素对象
Student s1 = new Student(1,"one","1111");
Student s2 = new Student(2,"tow","2222");
Student s3 = new Student(3,"three","3333");
//把对象添加到集合中,重复加入了s3的数据
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s3);
//创建一个新集合 用于比较和装载验证过的数据
ArrayList<Student> newList = new ArrayList<Student>();
//采用Iterator 遍历list
Iterator it = list.iterator();
while(it.hasNext()){
Student s = (Student)it.next();
if(!newList.contains(s)){
newList.add(s);
}
}
以上执行完就处理成功了,总结一下知识点:
-
为什么要重写equals方法?因为contains方法源码就是比较的equals方法,如下图,在比较contains方法的时候可以在entity重写
的Equals方法处打断点调试。
-
contains方法:如果此列表包含指定的元素,则返回true 。 更正式地说,返回true当且仅当此列表包含至少一个元素e这样(o==null ? e==null : o.equals(e))。
-
为何要去用一个新的newList去判断contains? 因为遍历原list后,第一条数据去比较,必然为不存在,所以加进去,再去原list拿第二条和新的newList去比较是否重复,不重复,加进来,如此一条条的去实现。明白?