开发过程中,有些数据查询出来后,需要通过代码再处理一遍,通常sql查询出来的数据,list集合中是对象,根据一些值来判断是否重复
示例
public class Student {
private String name;
private String code;
private String id;
private String time;
}
package com.test2;
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static void main(String[] args) {
/**
*
* 利用list去重
* */
Student tom = new Student("tom", "002", "1", "1997");
Student tom2 = new Student("tom", "002", "1", "1998");
Student tom3 = new Student("tom", "002", "1", "1999");
Student tom4 = new Student("tom4", "002", "1", "2000");
Student tom5 = new Student("tom4", "002", "1", "2001");
Student jack = new Student("jack", "001", "1", "1997");
Student jack2 = new Student("jack", "001", "1", "1998");
Student marry = new Student("marry", "003", "1", "1997");
Student marry2 = new Student("marry", "003", "1", "1998");
List<Student> list = new ArrayList();
list.add(tom);
list.add(tom2);
list.add(tom3);
list.add(tom4);
list.add(tom5);
list.add(jack);
list.add(jack2);
list.add(marry);
list.add(marry2);
System.out.println("原list"+list);
for (int i =0 ;i<list.size();i++){
for(int j=i+1;j<list.size();j++){
if(list.get(i).getCode().equals(list.get(j).getCode()) &&
list.get(i).getId().equals(list.get(j).getId())&&
list.get(i).getName().equals(list.get(j).getName())){
/**
* 每一次删除都需要重置,因为list的长度会变,需要重头开始
* */
list.remove(i);
i = 0;
j = 0;
}
}
}
System.out.println("去重后list"+list);
}
}
去重后的结果,这个例子是根据code,name,id去判断,可以根据实际情况去修改判断条件
原list[Student{name='tom', code='002', id='1', time='1997'}, Student{name='tom', code='002', id='1', time='1998'}, Student{name='tom', code='002', id='1', time='1999'}, Student{name='tom4', code='002', id='1', time='2000'}, Student{name='tom4', code='002', id='1', time='2001'}, Student{name='jack', code='001', id='1', time='1997'}, Student{name='jack', code='001', id='1', time='1998'}, Student{name='marry', code='003', id='1', time='1997'}, Student{name='marry', code='003', id='1', time='1998'}]
去重后list[Student{name='tom', code='002', id='1', time='1999'}, Student{name='tom4', code='002', id='1', time='2001'}, Student{name='jack', code='001', id='1', time='1998'}, Student{name='marry', code='003', id='1', time='1998'}]