将List中的对象中的字段的重复值删除


如下面的对象 Subs,如果其属性 startSt 和 endSt 同时有重复的值,则删除其中重复的一个。

 

主要代码:

List<Subs> results = new CopyOnWriteArrayList<Subs>();

for (Object obj : list) {
if (!results.contains(obj)) {
results.add((Subs) obj);
}
}

 

 

注:对象 Subs 中必须要重写 equals 方法。

 

class Subs {

private String startSt;
private String endSt;

public String toString() {

StringBuilder buf = new StringBuilder();

buf.append("Subs:[");
buf.append("startSt=").append(startSt).append(", ");
buf.append("endSt=").append(endSt);
buf.append("]");

return buf.toString();
}

public boolean equals(Object obj) {
if (obj == null) {
return false;
}

if (obj instanceof Subs) {

Subs other = (Subs) obj;

if (this.getStartSt().equals(other.getStartSt())
&& this.getEndSt().equals(other.getEndSt())) {
return true;
}
}

return false;
}

// 省略 setter/getter
}

 

测试(junit4):

 

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.junit.Test;

@Test
public void test() {

List<Subs> list = new LinkedList<Subs>();

Subs s1 = new Subs();

s1.setStartSt("桂林变");
s1.setEndSt("罗平站");

list.add(s1);

Subs s2 = new Subs();

s2.setStartSt("桂林变");
s2.setEndSt("挡村变电站");

list.add(s2);

Subs s3 = new Subs();

s3.setStartSt("国安站");
s3.setEndSt("尖峰站");

list.add(s3);

Subs s4 = new Subs();

s4.setStartSt("迁岗站");
s4.setEndSt("庙岭站");

list.add(s4);

Subs s5 = new Subs();

s5.setStartSt("迁岗站");
s5.setEndSt("庙岭站");

list.add(s5);

System.out.println("去重前:" + list);

List<Subs> results = new CopyOnWriteArrayList<Subs>();

for (Object obj : list) {
if (!results.contains(obj)) {
results.add((Subs) obj);
}
}

System.out.println("去重后:" + results);
}

 

重复的数据是:startSt=迁岗站, endSt=庙岭站

 

结果:

去重前:[Subs:[startSt=桂林变, endSt=罗平站], Subs:[startSt=桂林变, endSt=挡村变电站], 
Subs:[startSt=国安站, endSt=尖峰站], Subs:[startSt=迁岗站, endSt=庙岭站],
Subs:[startSt=迁岗站, endSt=庙岭站]]


去重后:[Subs:[startSt=桂林变, endSt=罗平站], Subs:[startSt=桂林变, endSt=挡村变电站],
Subs:[startSt=国安站, endSt=尖峰站], Subs:[startSt=迁岗站, endSt=庙岭站]]

 

 

 

 

本站声明
本文转载自:http://xurichusheng.iteye.com/blog/2260763     作者:xurichusheng     发布日期:2015-12-01     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2016 ITdaan.com 粤ICP备14056181号