Geek_To_Learn
Geek_To_Learn

Reputation: 1966

checking whether an object is present in a List of Objects on the basis of some member variable

suppose I have defined a List as

private BlockingQueue<MyDelayed> DelayedIds = new DelayQueue<>();

class MyDelayed is like: private class MyDelayed implements Delayed {

    private String myId;
    private Long creationTime;

    MyDelayed (String myId) {
       this.myId= myId;
       this.creationTime = System.currentTimeMillis();
    }

    String getMyId() {
        return this.myId;
    }

    @Override
    public long getDelay(TimeUnit unit) {
      //TODO
    }

    @Override
    public int compareTo(Delayed o) {
        //TODO
    }  
}

Now suppose that I want to add an Object of class MyDelayed in DelayedIds list. I can do it by using add function.

But If I want to add obbject in list only if list does not contain an object of class MyDelayed which has the same myId attribute which I am trying to insert.

Obviously DelayedIds .contains(new MyDelayed(myId)) will not work.

Is there any easy way to check this thing ? Am I missing something ?

Upvotes: 0

Views: 35

Answers (1)

ᴘᴀɴᴀʏɪᴏᴛɪs
ᴘᴀɴᴀʏɪᴏᴛɪs

Reputation: 7529

You could write something like this and compare every element in the list to see if it contains your id. If at any point you find a matching one you return true, if the loop finished having found none it returns false.

public boolean contains(String id){
    for (MyDelayed md : DelayedIds){ 
        if(md.getMyId().equals(id)){
            return true;
        }
    }
    return false;
}

Now to check before adding you would do something like:

if(!contains(myNewObject.getMyId())){
    DelayedIds.add(myNewObject)
}

Also, I'd suggest that you rename DelayedIds to delayedIds in order to follow coding standards (see Variables).

Upvotes: 1

Related Questions