假设我们有一个' 客户'对象:
public class Client {
private Long clientId;
private String clientName;
private Integer status;
//getters and setters for above attributes
.....
...
//hashCode method
....
..
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Client other = (Client) obj;
if (clientId == null) {
if (other.clientId != null)
return false;
} else if (!clientId.equals(other.clientId))
return false;
if (clientName == null) {
if (other.clientName != null)
return false;
} else if (!clientName.equals(other.clientName))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
}
从上述等同方法中可以清楚地知道' two'如果两个对象的所有属性相同,则称客户端对象相等。
现在假设我需要比较Client对象的两个集合(命名为incomingClients和existingClients)。 第一个集合(Collection incomingClients)是在阅读'客户端'来自csv / xls文件的数据 第二个集合(Collection existingClients)包含当前系统中的所有现有客户端。
我可以使用以下代码(使用apache CollectionUtils)来获取常见的#39;客户端。
Collection<Client> commonClients = (Collection<Client>)CollectionUtils.intersection(incomingClients,existingClients);
现在使用下面的代码我可以从两个集合中删除这些commonClients。
incomingClients.removeAll(commonClients);
existingClients.removeAll(commonClients);
删除“常见客户”对象的意图&#39;是的,我们不需要做任何处理&#39;对于这些记录, 因为我们对这些记录根本不感兴趣。
现在我怎样才能弄清楚哪些是全新的客户&#39;在&#39; Collection incomingClients&#39;采集? (当我说&#39; new&#39;这意味着客户有一个新的&#39; clientId&#39;它不存在于&#39; Collection existingClients&#39;) < / p>
另外,如何确定哪些客户需要修改&#39; (当我说&#39;修改&#39;这意味着&#39;收集来自客户&#39;和收集现有客户&#39; 拥有相同的clientId,但是,例如,不同的&#39; clientName&#39;)
我知道我们可以做正常的事情&#39;循环(&#39;检查以下&#39;)以找出所需的新修改&#39;客户端。
Collection<Client> newClients = new ArrayList<Client>();
Collection<Client> toBeModifiedClients = new ArrayList<Client>();
boolean foundClient = false;
Client client = null;
for(Client incomingClient :incomingClients){
foundClient = false;
for(Client existingClient : existingClients){
if(existingClient.getClientId().equals(incomingClient.getClientId())){
client = existingClient;
foundClient = true;
break;
}
}
if(foundClient){
toBeModifiedClients.add(client);
}else{
//not found in existing. so this is completely new
newClients.add(incomingClient);
}
}
我是不是很复杂&#39;一个简单的东西? 有什么想法??
答案 0 :(得分:0)
首先,是的,你让“简单的东西”复杂化了。您的整个问题可归纳如下:
鉴于集合A和B,我如何使用
CollectionUtils
获得以下内容:
- A-B,使用确定相等的特定函数
- A∩B,使用确定相等的特定函数
醇>
所以,是的。 CollectionUtils
拥有您所需要的。看看CollectionUtils.select()
。