如下面的对象 Subs,如果其属性 startSt 和 endSt 同时有重复的值,则删除其中重复的一个。
主要代码:
Listresults = new CopyOnWriteArrayList (); 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() { Listlist = new LinkedList (); 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 results = new CopyOnWriteArrayList (); 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=庙岭站]]