Java List.contains(Object with field value equal to x)

I want to check whether a List contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient.

Something like;

if(list.contains(new Object().setName("John"))){
    //Do some stuff
}

I know the above code doesn’t do anything, it’s just to demonstrate roughly what I am trying to achieve.

Also, just to clarify, the reason I don’t want to use a simple loop is because this code will currently go inside a loop that is inside a loop which is inside a loop. For readability I don’t want to keep adding loops to these loops. So I wondered if there were any simple(ish) alternatives.

13 Answers
13

Leave a Comment