How to Check If a List Contains Object by Field in Java


Let’s see how we can check if a list of objects contains an object with a specific field in Java.

Suppose we have a list of people (i.e. List<Person>), and we want to check if it contains a person with a name of John Doe.

1. Using the Stream API

1.1. Using anyMatch()

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

1.2. Using filter()

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

1.3. Using map() and filter()

boolean contains(List<Person> list, String name) {
  return list.stream().map(Person::getName).filter(name::equals).findFirst().isPresent();
}

2. Overriding equals() and hashcode()

If we know that the name of our Person object is the only unique attribute (i.e. two objects are considered equal with the names are equal), then we might want to override the equals() and hashcode() method.

Then, we can compare objects in our list against another object using contains().

boolean contains(List<Person> list, Person person) {
  return list.contains(person)
}

3. Using Guava

We can also use FluentIterable from Guava, which will match elements from the list based on some Predicate.

boolean contains(List<Person> list, String name) {
  return FluentIterable.from(list).anyMatch(new Predicate<Person>() {
    @Override
    public boolean apply(@Nullable Person input) {
      return input.getName().equals(name);
    }
  });
}

4. Using a map or dictionary

If we plan on perform this lookup many times, we can also convert our list of objects to a map (i.e. Hashmap<String, Person>), where the key is the attribute to lookup (e.g. name) and the value is the object (e.g. Person).

We might convert a list to map like so:

Map<String, Person> map = 
  list.stream().collect(
    Collectors.toMap(
      Person::getName, 
      person -> person
    )
  );

Then, we can check for the existence of the key using contains().

boolean contains(HashMap<String, Person> map, String name) {
  return map.keySet().contains(name);
}