Java 比较两个集合并删除常用项
我有两个集合,其中包含一些元素作为对象。我想从集合中删除公共元素。如何从集合中删除公共元素Java 比较两个集合并删除常用项,java,Java,我有两个集合,其中包含一些元素作为对象。我想从集合中删除公共元素。如何从集合中删除公共元素 Set<AcceptorInventory> updateList = new HashSet<AcceptorInventory>(); Set<AcceptorInventory> saveList = new HashSet<AcceptorInventory>(); AcceptorInventory哈希代码和等于 @Override public
Set<AcceptorInventory> updateList = new HashSet<AcceptorInventory>();
Set<AcceptorInventory> saveList = new HashSet<AcceptorInventory>();
AcceptorInventory哈希代码和等于
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + count;
result = prime * result
+ ((currency == null) ? 0 : currency.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + (isCleared ? 1231 : 1237);
result = prime * result
+ ((kioskMachine == null) ? 0 : kioskMachine.hashCode());
result = prime * result + ((time == null) ? 0 : time.hashCode());
long temp;
temp = Double.doubleToLongBits(total);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AcceptorInventory other = (AcceptorInventory) obj;
if (count != other.count)
return false;
if (currency == null) {
if (other.currency != null)
return false;
} else if (!currency.equals(other.currency))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (id != other.id)
return false;
if (isCleared != other.isCleared)
return false;
if (kioskMachine == null) {
if (other.kioskMachine != null)
return false;
} else if (!kioskMachine.equals(other.kioskMachine))
return false;
if (time == null) {
if (other.time != null)
return false;
} else if (!time.equals(other.time))
return false;
if (Double.doubleToLongBits(total) != Double
.doubleToLongBits(other.total))
return false;
return true;
}
将从updateList
中删除saveList
的所有元素
如果您还想从保存列表
中删除更新列表
的元素,则必须先创建其中一个集合的副本:
Set<AcceptorInventory> copyOfUpdateList = new HashSet<>(updateList);
updateList.removeAll (saveList);
saveList.removeAll (copyOfUpdateList);
Set copyOfUpdateList=新哈希集(updateList);
updateList.removeAll(保存列表);
saveList.removeAll(copyOfUpdateList);
请注意,为了使您的
AcceptorInventory
作为HashSet
的元素正常工作,它必须重写equals
和hashCode
方法,任何两个相等的AcceptorInventory
必须具有相同的hashCode
您可以使用
saveList.removeAll(updateList);
您是否重写了
equals
和hashCode
方法?否则,除非列表包含相同的对象引用,否则您将无法删除它们working@tyson当我在集合上测试它时,它对我有效。可能您的AcceptorInventory
没有正确覆盖equals
和hashCode
。我已经用integer和string进行了测试,它工作正常。但是它在使用AcceptorInventory时不起作用。@tyson请参阅我的编辑。您必须重写equals
和hashCode
。我已经添加了equals和hashCode,但没有工作项列表从列表中删除使用removeAll或通过迭代该列表删除项如果其中一个集合为空,您如何处理
Set<AcceptorInventory> copyOfUpdateList = new HashSet<>(updateList);
updateList.removeAll (saveList);
saveList.removeAll (copyOfUpdateList);
saveList.removeAll(updateList);