日期:2014-05-20  浏览次数:20929 次

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重复的对象呢?
}


我想去掉Temp对象中字段b重复的对象,上面的例子就是temp1和temp2。

除了使用双重for循环从第一个开始逐个和后面的遍历remove之外,有没有什么快速的方法呢?
------最佳解决方案--------------------
map呢 键值 无重复数据。 把您要去重的那个字段作为键
------其他解决方案--------------------
对了   需要转换成 ArrayList 在用用hashcode 和 hashset 去重复
------其他解决方案--------------------
用hashcode 和 hashset 去重复
------其他解决方案--------------------
hashcode不一样

引用:
对了   需要转换成 ArrayList 在用用hashcode 和 hashset 去重复

------其他解决方案--------------------

//如何去除字段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());


这样能去除后面重复的...对第一次出现的这个temp1就无能为例了...除非在循环一遍,把map里面key存在的对象处理一遍。。。

就这样吧....

引用:
map呢 键值 无重复数据。 把您要去重的那个字段作为键

------其他解决方案--------------------
估计我写的这个不是你想表达的...
引用:
map呢 键值 无重复数据。 把您要去重的那个字段作为键