![](/img/trans.png)
[英]Java Stream over a list and check if the list contains at list one object with one of three given field values
[英]check if a list already contains an object with similar values - java
仅当给定列表尚未包含具有相似属性的对象时,才需要将对象添加到列表中
List<Identifier> listObject; //list
Identifier i = new Identifier(); //New object to be added
i.type = "TypeA";
i.id = "A";
if(!listObject.contains(i)) { // check
listObject.add(i);
}
我尝试了contains()
对现有列表进行检查。 如果列表中已有对象,则说j
与j.type = "TypeA"
和j.id = "A"
,我不想将其添加到列表中。
您能否通过覆盖等于或任何可行的解决方案来帮助我实现这一目标?
在您的Identifier
类中实现equals()
和hashCode()
。
如果不想在添加元素之前执行检查,则可以将listObject
从List
更改为Set
。 Set
是不包含重复元素的集合。
遵循由Eclipse IDE自动创建的实现示例:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Identifier other = (Identifier) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.