找出对象列表是否包含具有指定字段值的内容? [英] Finding out if a list of Objects contains something with a specified field value?
问题描述
我有一个从数据库收到的 DTO 列表,它们有一个 ID.我想确保我的列表包含具有指定 ID 的对象.显然,在这种情况下创建具有预期字段的对象无济于事,因为 contains() 调用 Object.equals(),并且它们不会相等.
I have a list of DTO received from a DB, and they have an ID. I want to ensure that my list contains an object with a specified ID. Apparently creating an object with expected fields in this case won't help because contains() calls for Object.equals(), and they won't be equal.
我想出了一个这样的解决方案:创建一个接口 HasId
,在我所有的 DTO 中实现它,并用一个具有 contains(Long id)
的新类继承 ArrayList代码>方法.
I came up to a solution like so: created an interface HasId
, implemented it in all my DTOs, and inherited ArrayList with a new class that has contains(Long id)
method.
public interface HasId {
void setId(Long id);
Long getId();
}
public class SearchableList<T extends HasId> extends ArrayList<T> {
public boolean contains(Long id) {
for (T o : this) {
if (o.getId() == id)
return true;
}
return false;
}
}
但在这种情况下,我无法将 List 和 ArrayList 类型转换为 SearchableList ...我愿意接受,但想确保我不是在发明轮子.
But in this case I can't typecast List and ArrayList to SearchableList... I'd live with that, but wanted to make sure that I'm not inventing the wheel.
编辑(2016 年 10 月):
EDIT (Oct '16):
当然,随着 Java 8 中 lambdas 的引入,实现这一点的方法很简单:
Of course, with the introduction of lambdas in Java 8 the way to do this is straightforward:
list.stream().anyMatch(dto -> dto.getId() == id);
推荐答案
我建议像你写的那样创建简单的静态方法,不需要任何额外的接口:
I propose to create simple static method like you wrote, without any additional interfaces:
public static boolean containsId(List<DTO> list, long id) {
for (DTO object : list) {
if (object.getId() == id) {
return true;
}
}
return false;
}
这篇关于找出对象列表是否包含具有指定字段值的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!