Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

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

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...