在實際開發中,需要對比兩個json文件,兩個文件中可能有相同的數據,也可能有不同的數據,去掉兩個文件中相同的數據,將第一個文件的數據標記爲del,第二個文件的數據標記爲add,並用csv文件進行保存。
1.removeAll()
List<RdsSO> beginRdsList = jsonToList(InJsonPath + File.separator + "DCI-" +date1 + "003000.json");
List<RdsSO> endRdsList = jsonToList(InJsonPath + File.separator + "DCI-" + date2 + "003000.json");
//對兩個list中重複的數據進行去重,只留下不同的數據
List<RdsSO> beginRdsList1 = new ArrayList<RdsSO>();
List<RdsSO> endRdsList1 = new ArrayList<RdsSO>();
beginRdsList1.addAll(beginRdsList);
beginRdsList1.removeAll(endRdsList);
endRdsList1.addAll(endRdsList);
endRdsList1.removeAll(beginRdsList);
其中,jsonToList是我自己定義的一個方法,就是讀取json文件並對對象進行賦值,存儲到List中。
此時,我們需要對RdsSo實體類中的equals()和hashCode()方法進行重寫,這樣可以根據你的需求屬性對對象進行去重。beginRdsList1和endRdsList1就是我們去重後的數據。
在本文中,是根據id屬性進行去重的,只要id一致,就可以看作是一個對象。
public class RdsSO implements Serializable {
private String id;
private String operType;
private String vpnType;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOperType() {
return operType;
}
public void setOperType(String operType) {
this.operType = operType;
}
public String getVpnType() {
return vpnType;
}
public void setVpnType(String vpnType) {
this.vpnType = vpnType;
}
public RdsSO(){
}
public RdsSO(String id, String operType, String vpnType) {
this.id = id;
}
@Override
public int hashCode(){
String result = id;
return result.hashCode();
}
@Override
public boolean equals(Object obj){
RdsSO rdsSO =(RdsSO)obj;
return this.getId().equals(rdsSO.getId() );
}
}
2.retaiAll()
與上面的類似,不過結果集List留下的是兩個集合重複的數據。