找出对象列表中是否包含具有指定字段值的内容?

发布于 2024-12-05 08:34:45 字数 815 浏览 1 评论 0原文

我有一个从数据库收到的 DTO 列表,并且它们有一个 ID。我想确保我的列表包含具有指定 ID 的对象。显然,在这种情况下创建具有预期字段的对象不会有帮助,因为 contains() 调用 Object.equals(),并且它们不会相等。

我想出了这样的解决方案:创建一个接口 HasId,在我的所有 DTO 中实现它,并使用具有 contains(Long id) 方法的新类继承 ArrayList 。

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... 我愿意接受这一点,但想确保我没有发明轮子。

编辑(16 年 10 月):

当然,随着 Java 8 中引入 lambda,执行此操作的方法很简单:

list.stream().anyMatch(dto -> dto.getId() == id);

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.

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

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.

EDIT (Oct '16):

Of course, with the introduction of lambdas in Java 8 the way to do this is straightforward:

list.stream().anyMatch(dto -> dto.getId() == id);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

七度光 2024-12-12 08:34:45

我建议像您编写的那样创建简单的静态方法,而不需要任何额外的接口:

public static boolean containsId(List<DTO> list, long id) {
    for (DTO object : list) {
        if (object.getId() == id) {
            return true;
        }
    }
    return false;
}

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;
}
泛滥成性 2024-12-12 08:34:45

我建议您只需覆盖 SearchableDto 中的 equals ,它会类似于:

public boolean equals(Object o){
    if (o instanceof SearchableDto){
        SearchableDto temp = (SearchableDto)o;
        if (this.id.equals(temp.getId()))
            return true;
    }
    return false;
}

在这种情况下,如果 contains 具有相同的 <代码>id;

I suggest you just override the equals in your SearchableDto it would be something like:

public boolean equals(Object o){
    if (o instanceof SearchableDto){
        SearchableDto temp = (SearchableDto)o;
        if (this.id.equals(temp.getId()))
            return true;
    }
    return false;
}

In this case contains should work probably if it has the same id;

秋叶绚丽 2024-12-12 08:34:45

嗯,我认为你的方法有点让问题复杂化了。
你说:

我有一个从数据库收到的 DTO 列表,并且它们有一个 ID。

那么您可能应该使用 DTO 类来保存这些项目。如果是这样,请将 id getter 和 setter 放入该类中:

public class DTO implements HasId{
    void setId(Long id);
    Long getId();
}

这足以遍历 ArrayList 并搜索所需的 id。
仅为了添加“compare-id”功能而扩展 ArrayList 类对我来说似乎过于复杂。 @Nikita Beloglazov 就是一个很好的例子。你还可以进一步概括它:

public boolean containsId(List<HasId> list, long id) {
    for (HasId object : list) {
        if (object.getId() == id) {
            return true;
        }
    }
    return false;
}

Well, i think your approach is a bit overcomplicating the problem.
You said:

I have a list of DTO received from a DB, and they have an ID.

Then probably you should use a DTO class to hold those items. If so put id getter and setter inside that class:

public class DTO implements HasId{
    void setId(Long id);
    Long getId();
}

That's enough for iterate through and ArrayList and search for the desired id.
Extending ArrayList class only for adding the "compare-id" feautre seems overcomplicated o me. @Nikita Beloglazov make a good example. You can generalize it even more:

public boolean containsId(List<HasId> list, long id) {
    for (HasId object : list) {
        if (object.getId() == id) {
            return true;
        }
    }
    return false;
}
哽咽笑 2024-12-12 08:34:45

这是我在 DFS GetUnvisitedNeighbour 函数中使用的。

    public static int GetUnvisitedNeighbour(int v)
{
    Vertex vertex = VertexList.stream().filter(c -> c.Data == v).findFirst().get();
    int position = VertexList.indexOf(vertex);
    ...
}

我以前从事 C# 工作。 C# 中的 Lambda 表达式比 Java 中的更容易使用。

您可以使用filter函数为元素的属性添加条件。

然后根据您的逻辑使用 findFirst().get()findAny.get()

This is what I used in my DFS GetUnvisitedNeighbour function.

    public static int GetUnvisitedNeighbour(int v)
{
    Vertex vertex = VertexList.stream().filter(c -> c.Data == v).findFirst().get();
    int position = VertexList.indexOf(vertex);
    ...
}

I used to work in C#. Lambda expressions in C# are much easier to work with than they are in Java.

You can use filter function to add condition for property of element.

Then use findFirst().get() or findAny.get() according to your logic.

世态炎凉 2024-12-12 08:34:45

你的要求我不清楚。当您说“确保我的列表包含具有指定 ID 的对象”时,您是否想要:

  1. 检测 ID 是否存在并采取相应行动
  2. 始终在结果中包含具有所需 ID 的 DTO

大多数响应都假设您的意思是 1当考虑这个问题时,考虑到问题的措辞,你也可以指2。您可以通过更改查询来包含所需的结果:

SELECT * FROM employee WHERE firstname = 'John' OR id = 42;

You requirement is not clear to me. When you say 'ensure that my list contains an object with a specified ID' do you want to:

  1. detect if the ID is present and act accordingly
  2. always include the DTO with the required ID in your results

Most responses have assumed you mean 1, however when thinking about it you could just as well mean 2 given the wording of the question. You could include the required result by altering your query:

SELECT * FROM employee WHERE firstname = 'John' OR id = 42;
命硬 2024-12-12 08:34:45
   public boolean containsId(List<HasId> list, long id) {
    boolean flag = false;
    for (HasId object : list) {
        if (object.getId() == id) {
           flag = true;
        }
    }
    return flag;
}
   public boolean containsId(List<HasId> list, long id) {
    boolean flag = false;
    for (HasId object : list) {
        if (object.getId() == id) {
           flag = true;
        }
    }
    return flag;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文