有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java比较两个集合并删除常用项

我有两个集合,其中包含一些元素作为对象。我想从集合中删除公共元素。如何从集合中删除公共元素

Set<AcceptorInventory> updateList = new HashSet<AcceptorInventory>();
Set<AcceptorInventory> saveList = new HashSet<AcceptorInventory>();

两组都有一些项目,saveList有重复的项目&;我希望从saveList中删除重复的项目。我尝试了foreach循环,但没有成功

样本输出:

save 5
save 20
save 50
save 10
update 5
update 10
update 20

AcceptorInventory哈希代码和equals

@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;
}

共 (2) 个答案

  1. # 1 楼答案

    updateList.removeAll(saveList);
    

    将从updateList中删除saveList的所有元素

    如果还想从saveList中删除updateList的元素,则必须先创建其中一个集合的副本:

    Set<AcceptorInventory> copyOfUpdateList = new HashSet<>(updateList);
    updateList.removeAll (saveList);
    saveList.removeAll (copyOfUpdateList);
    

    请注意,为了使AcceptorInventory作为HashSet的元素正常工作,它必须覆盖equalshashCode方法,任何两个相等的AcceptorInventory都必须具有相同的hashCode

  2. # 2 楼答案

    您可以使用从当前存储列表中删除常用项

    saveList.removeAll(updateList);