JAVA-List对象某个字段去重
本帖最后由 isea533 于 2012-10-29 16:46:08 编辑 List对象去重的算法
return new ArrayList<T>(new LinkedHashSet<T>(list))
public static void main(String[] args) {
class Temp{
private int a;
private String b;
private BigInteger cBigInteger;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public BigInteger getcBigInteger() {
return cBigInteger;
}
public void setcBigInteger(BigInteger cBigInteger) {
this.cBigInteger = cBigInteger;
}
}
Temp temp1 = new Temp();
temp1.setA(10);
temp1.setB("hehe");
temp1.setcBigInteger(new BigInteger("1111111111111111111111111"));
Temp temp2 = new Temp();
temp2.setA(10);
temp2.setB("hehe");
temp2.setcBigInteger(new BigInteger("1111111111111111111111111"));
Temp temp3 = new Temp();
temp3.setA(10);
temp3.setB("hehe3");
temp3.setcBigInteger(new BigInteger("1111111111111111111111111"));
Temp temp4 = new Temp();
temp4.setA(10);
temp4.setB("hehe4");
temp4.setcBigInteger(new BigInteger("1111111111111111111111111"));
List<Temp> list = new ArrayList<Temp>();
list.add(temp1);
list.add(temp2);
list.add(temp3);
list.add(temp4);
//如何去除字段b重复的对象呢?
}
//如何去除字段b重复的对象呢?
System.out.println(list.size());
HashMap<String, String> map = new HashMap<String, String>();
for(int i=0;i<list.size();i++){
if(map.get(list.get(i).getB())!=null){
list.remove(i);
}
else {
map.put(list.get(i).getB(), "OK");
}
}
System.out.println(list.size());