Finding out if a list of Objects contains something with a specified field value?

前端 未结 6 2085
遥遥无期
遥遥无期 2020-12-03 10:20

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 expect

6条回答
  •  萌比男神i
    2020-12-03 10:21

    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 list, long id) {
        for (HasId object : list) {
            if (object.getId() == id) {
                return true;
            }
        }
        return false;
    }
    

提交回复
热议问题