Java
Programming
Data Structures
Object Oriented Programming
Java List API

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

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

In Java, the List interface is a fundamental component of the java.util package, providing a powerful way to store and manage collections of objects. Among the various methods offered by the List interface, contains(Object o) is particularly useful for checking if a list contains an element that satisfies a certain condition. However, when it comes to checking whether a list contains an object with a specific field value, contains needs a bit of help.

Understanding List.contains(Object o)

The contains method checks whether the list contains an element equal to the specified object o. Under the hood, this method typically calls equals(Object o) on the elements of the list. The equals method must be overridden in the class of the object to ensure the contains method works as expected for customized equality checks.

Customizing Object Equality

To determine if a list contains an object with a specific field value, you must ensure that the equals method in your object's class is tailored to compare the desired field values. Consider an example with a class Person:

java
1public class Person {
2    private String name;
3    private int age;
4
5    public Person(String name, int age) {
6        this.name = name;
7        this.age = age;
8    }
9
10    @Override
11    public boolean equals(Object obj) {
12        if (this == obj) return true;
13        if (obj == null || getClass() != obj.getClass()) return false;
14        Person person = (Person) obj;
15        return age == person.age && Objects.equals(name, person.name);
16    }
17
18    @Override
19    public int hashCode() {
20        return Objects.hash(name, age);
21    }
22}

Here, equals is overridden to check both the name and the age. If you want to check only by name, then you would modify the equals method accordingly.

Using contains with Custom Objects

Suppose you have a list of Person objects and you want to find if there is a person named "John" in the list. If you have overridden equals to compare only names, contains will work directly:

java
1List<Person> people = new ArrayList<>();
2people.add(new Person("John", 25));
3people.add(new Person("Alice", 30));
4
5boolean containsJohn = people.contains(new Person("John", 0));  // age is irrelevant here
6System.out.println("Contains John? " + containsJohn);

Efficient Searching with Stream API

Alternatively, if modifying the equals method is not suitable (for instance, because you need to check different fields in different situations), you can use the Java Stream API for more flexibility:

java
boolean containsJohn = people.stream()
                             .anyMatch(p -> "John".equals(p.getName()));
System.out.println("Contains John? " + containsJohn);

This example doesn't require changing the equals method and allows specific field checks dynamically at runtime.

Summary Table

Here is a concise summary of the key points discussed:

MethodPurposeUsage Considerations
List.containsChecks if a list contains an object based on equalsEnsure equals method is correctly overridden in the object class
Stream.anyMatchFinds if any element of a stream matches a conditionMore flexible for dynamic, runtime field-based checks

Additional Considerations

When using contains or Stream.anyMatch, it's important to consider performance implications especially for large lists. contains runs in O(n)O(n) time for a list, while Stream.anyMatch also performs similarly but may benefit from parallelism if working with a parallel stream.

In conclusion, List.contains(Object o) is a powerful method when used appropriately with a correctly overridden equals method. For more complex or dynamic searching, the Stream API provides a robust alternative.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.