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

To check if a Java List contains an object with a specific field value, you can use the List.stream().anyMatch() method along with a lambda expression to filter the elements in the list based on the field value.

For example, suppose you have a Person class with a name field, and you want to check if a List<Person> contains a person with a specific name. You can do it like this:

boolean containsName(List<Person> list, String name) {
    return list.stream().anyMatch(p -> p.getName().equals(name));
}

This will return true if the list contains at least one person with the given name, and false otherwise.

Alternatively, you can use the List.stream().filter().count() method to count the number of elements in the list that match the given condition, and check if the count is greater than zero:

boolean containsName(List<Person> list, String name) {
    return list.stream().filter(p -> p.getName().equals(name)).count() > 0;
}

You can also use the List.stream().filter().findAny().isPresent() method to check if there is at least one element in the list that matches the given condition:

boolean containsName(List<Person> list, String name) {
    return list.stream().filter(p -> p.getName().equals(name)).findAny().isPresent();
}

Finally, you can use the List.stream().filter().findFirst().isPresent() method to check if the first element in the list that matches the given condition is present:

boolean containsName(List<Person> list, String name) {
    return list.stream().filter(p -> p.getName().equals(name)).findFirst().isPresent();
}