最近帮朋友做项目,自己也在学习数据结构和算法分析,发现要想项目高效率的运行,数据结构和算法是必须要掌握的一门技术,刚好项目中就碰到了处理数据的地方。
首先我先说说需求吧,有两个集合A、B,在A集合去除B集合中People对象的数据,只要A集合中People的name和subList集合中People的name相同就可以去除。怪我自己的语文功底不好,我直接上代码吧。
对象代码:
public class People {
private String name;
private int age;
private boolean isCheck;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean check) {
isCheck = check;
}
}
模拟需求代码:
ArrayList<People> mList = new ArrayList<>();
ArrayList<People> subList = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
People people = new People();
people.setAge(10 + i);
people.setName("jack" + i);
people.setCheck(false);
mList.add(people);
}
for (int i = 0; i < 10000; i++) {
People people = new People();
people.setAge(10 + i);
people.setName("jack" + i);
people.setCheck(true);
subList.add(people);
}
//在mList集合去除subList集合中People对象的数据,只要mList集合中People的name和subList集合中People的name相同
//就可以去除
接下来我说说两种实现方法
双层for循环
刚开始为了实现功能,我用了这种方式,不过我对这种实现方式非常不满,下面贴出我实现的代码
for (People people : subList) {
for (int i = 0; i < mList.size(); i++) {
if (people.getName().equals(mList.get(i).getName())) {
mList.remove(i);
}
}
}
刚开始用了几十条数据进行测试,
看不出来效率怎么样,后来我用了10000条数据进行测试,发现耗时需要330毫秒
2.利用set集合不重复来进行实现
直接上代码吧
/**
* 将列表中重复的用户移除,重复指的是name相同
*
* @param userList
* @return
*/
public static ArrayList<People> removeDuplicteUsers(ArrayList<People> userList) {
Set<People> s = new TreeSet<People>(new Comparator<People>() {
@Override
public int compare(People o1, People o2) {
return o1.getName().compareTo(o2.getName());
}
});
s.addAll(userList);
return new ArrayList<People>(s);
}
我用了同样的方法测试,发现耗时竟然17毫秒,这种效率比双层for循环高出几十倍,如果再用更多的数据进行测试的话,效率会高出上百倍
可见一个好的实现方式,效率能高出上百倍,所以数据结构和算法是必不可少的,这个必须得学习掌握。