Search code examples
javalistsearchcontains

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.


Solution

  • Streams

    If you are using Java 8, perhaps you could try something like this:

    public boolean containsName(final List<MyObject> list, final String name){
        return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
    }
    

    Or alternatively, you could try something like this:

    public boolean containsName(final List<MyObject> list, final String name){
        return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
    }
    

    This method will return true if the List<MyObject> contains a MyObject with the name name. If you want to perform an operation on each of the MyObjects that getName().equals(name), then you could try something like this:

    public void perform(final List<MyObject> list, final String name){
        list.stream().filter(o -> o.getName().equals(name)).forEach(
                o -> {
                    //...
                }
        );
    }
    

    Where o represents a MyObject instance.

    Alternatively, as the comments suggest (Thanks MK10), you could use the Stream#anyMatch method:

    public boolean containsName(final List<MyObject> list, final String name){
        return list.stream().anyMatch(o -> name.equals(o.getName()));
    }