It's not the most efficient solution but the most terse code would be:

boolean equalLists = listA.size() == listB.size() && listA.containsAll(listB);

Update:

@WesleyPorter is right. The solution above will not work if duplicate objects are in the collection.
For a complete solution you need to iterate over a collection so duplicate objects are handled correctly.

private static boolean cmp( List<?> l1, List<?> l2 ) {
    // make a copy of the list so the original list is not changed, and remove() is supported
    ArrayList<?> cp = new ArrayList<>( l1 );
    for ( Object o : l2 ) {
        if ( !cp.remove( o ) ) {
            return false;
        }
    }
    return cp.isEmpty();
}

Update 28-Oct-2014:

@RoeeGavriel is right. The return statement needs to be conditional. The code above is updated.

Answer from Oded Peer on Stack Overflow
🌐
YouTube
youtube.com › java coding insight interview preparation
Comparing List of Objects Using Multiple Fields -Plain Java 8 Comparator - No Third Party Library - YouTube
If you find this video helpful, please 'Like' or 'Subscribe'. This is really helpful for the channel and also motivates me to do more of such good and usefu...
Published: September 30, 2021
Views: 5K
Discussions

java - How to compare a field between two Lists of objects? - Stack Overflow
Construct a Map of the Local supermarkets using the supermarketId as the key by running through the list once · Loop through the cloud list and do you comparison, looking up the local supermarket from your map. More on stackoverflow.com
🌐 stackoverflow.com
September 21, 2015
java - Comparing two lists by object fields - Stack Overflow
I can think of two ways to do this. Either equate all student objects in the input list and output lists using all fields except id. Or, manually injecting the id of each student in the input list with the output list's values. Both ways are pretty unclean in their implementation so I was hoping there was a clean way to do it? For example, in the first option I can sort both the input and output collections, then iterate the first collection and compare ... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
java - Determine if 2 lists with similar objects contain a partial duplicate - Code Review Stack Exchange
I have two lists of Person objects. I need to compare the lists to determine if items in list1 exist in list2 and vice versa. This is not a straight equals() scenario as the objects are not the sa... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 21, 2018
java - Comparing multiple fields of 2 list of different objects - Stack Overflow
I have two objects, both have 4 similar fields that I need to compare and I get them from different sources as a list of objects. I want to make sure that there is at least one matching object in b... More on stackoverflow.com
🌐 stackoverflow.com
November 10, 2017
🌐
Baeldung
baeldung.com › home › java › java list › finding the differences between two lists in java
Finding the Differences Between Two Lists in Java | Baeldung
April 29, 2026 - Finding differences between collections of objects of the same data type is a common programming task. As an example, imagine we have a list of students who applied for an exam, and another list of students who passed it. The difference between those two lists would give us the students who didn’t pass the exam. In Java, there’s no explicit way of finding the differences between two lists in the List API, though there are some helper methods that come close.
🌐
amitph
amitph.com › home › java › comparing two lists in java
Comparing Two Lists In Java - amitph
November 22, 2024 - Alternatively, we can use Java Streams API to find common elements between two Lists. To do that, we can create a Stream of the first List and use the filter() method to retain only the elements in the second List.
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › compare two lists in java: equality, differences, common items
Compare Two Lists in Java: Equality, Differences, Common Items
September 24, 2018 - Either the order differs, or the element class does not override equals(). Without the override, equals() compares object references, so two objects with the same fields are different. For equality ignoring order, a frequency map is linear. For differences and common items, we put one list into a HashSet and filter the other list, which is also linear, whereas list.contains() inside a loop is quadratic.
Find elsewhere
Top answer
1 of 4
3

The approach, algorithm

To find if an object exists in a list, you need to perform a linear search, potentially visiting every single element, in \$O(n)\$ time. More efficient data structures exist:

  • Use an ordered data structure: if the values are sorted, then you can find if an element exists using binary search, in \$O(\log n)\$ time.

  • Use a hashset: you can find if an element is in the set in constant time, \$O(1)\$

To be to search efficiently, use a hashset instead of a list. However, to be able to use a hashset efficiently, it is required that the objects you put in it have appropriate implementation of hashCode and equals methods.

See the official tutorial on the Object class, especially the sections on the equals and hashCode methods. Note that IDEs like IntelliJ and Eclipse can generate these methods for you easily (they are boring to write by hand, and usually there's little reason to do so).

With correct implementation of the equals and hashCode methods, for example as in the other answer by @Teddy, your main program could be reduced to this:

public static void main(String[] args) {

    Set<Person> originalPeople = new HashSet<>();
    Set<Person> newPeople = new HashSet<>();

    originalPeople.add(new Person("William", "Tyndale"));
    originalPeople.add(new Person("Jonathan", "Edwards"));
    originalPeople.add(new Person("Martin", "Luther"));

    newPeople.add(new Person("Jonathan", "Edwards"));
    newPeople.add(new Person("James", "Tyndale"));
    newPeople.add(new Person("Roger", "Moore"));

    for (Person original : originalPeople) {
        if (!newPeople.contains(original)) {
            System.out.printf("%s %s is not in the new list!%n",
                    original.getFirstName(), original.getLastName());
        }
    }
}
2 of 4
3

There are certain reasons I would not prefer your approach. These are:

1) There are multiple method calls which reduces the readability.

2) You are using filter twice which decreases the performances. You could do it inside the same filter like I've shown below

3) With this approach you don't have a consolidated List which contains common elements. For that you need another else condition which increases the cyclomatic complexity.

4) A null check which could produce NPE if not handled carefully as you are using findFirst() which returns Optional (Although null can be replaced with default new Person("","") object which is again not recommended).

5) Finally don't use ArrayList<Person> originalPeople = new ArrayList<>();; rather declare as List, to follow programming to interface.

Rather I would use below approach:

private static List<Person> getPersonInList(
            final List<Person> newPeople, List<Person> originalPeople) {
        List<Person> list = new ArrayList<>();

        newPeople.forEach(p ->
                originalPeople.stream()
                              .filter(p1 -> p.getFirstName().equals(p1.getFirstName()) && 
                                      p.getLastName().equals(p1.getLastName()))
                              .forEach(list::add));
        return list;
    }
🌐
CodingTechRoom
codingtechroom.com › question › -merge-lists-java
How to Merge Two Lists of Objects by Comparing Field Values in Java - CodingTechRoom
Merging two lists of objects based on a particular field involves comparing each object in the first list with every object in the second list. A common approach is to use a combination of Java's stream API and collectors or simple iteration ...
🌐
Javatpoint
javatpoint.com › how-to-compare-two-arraylist-in-java
How to Compare Two ArrayList in Java - Javatpoint
How to Compare Two ArrayList in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
🌐
javaspring
javaspring.net › blog › java-compare-two-list-s-object-values
Java: How to Compare Two Lists of Objects by Name and Boolean Values – Step-by-Step Guide
This guide will walk you through step-by-step methods to compare two lists of custom objects in Java, focusing on two common criteria: - A `name` field (String type) - A boolean field (e.g., `isActive`) By the end, you’ll understand how to handle both order-sensitive and order-insensitive ...
🌐
DZone
dzone.com › coding › languages › how to compare list objects in java 7 vs. java 8
How to Compare List Objects in Java 7 vs. Java 8 - DZone
June 1, 2018 - As an example, you have a List of Employee Objects and you need to check that all your Employees are above 18. One or more elements from one List match(es) the elements of another List. All elements of a List exist in another List. Now, developing these use cases is very easy in Java 7 with relatively few lines of code. The following is an example where we are comparing two Lists in Java 7 and checking if any element from List 1 exists in List 2.
🌐
Stack Overflow
stackoverflow.com › questions › 15203561 › comparing-two-object-lists-using-one-of-the-object-atributes
java - Comparing two object lists using one of the object atributes - Stack Overflow
You can also use Collection.removeAll on your list. It is not always practical to override equals, for example if you have different scenarios where you want to compare according to other attributes. In that case, you can use a Comparator and Collections2.filter from Guava library. ... The answer is no rtf Why you don't use Google to find it yourself Why you don't use the ide to show you the documentation · i thinlk override equals solve the problem but is a hack · import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String a
🌐
GeeksforGeeks
geeksforgeeks.org › java › compare-objects-by-multiple-fields-in-java
How to Compare Objects by Multiple Fields in Java? - GeeksforGeeks
July 23, 2025 - To compare objects by multiple fields in Java using a Custom Comparator, you can follow this approach, Suppose you have a class MyClass with fields field1, field2, and field3. You want to compare objects of this class first by field1, then by field2, and finally by field3...
🌐
Reddit
reddit.com › r/javahelp › how can i compare two lists of objects of the same size
r/javahelp on Reddit: How can I compare two lists of objects of the same size
October 4, 2023 -

I want to do a certain action each time an object is the same and at the same index and another action each time an object is present in both lists but not at the same index. It has to match though (i cant do the second action 4 times if both lists are like that ex :(r,f,f,f,f) (r, r, r, r, r) only once

Top answer
1 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 4
1
Im sure you can do it way more elegantly, but you can iterate the first list and save the current index, then for each object you’re iterating, you iterate the second list. If you have a match, you can write your condition/action and use a break to get out of the loop, so that you only have one match.
Top answer
1 of 1
1

I find the current algorithm of "adding and removing" to be a streamed implementation of non-functional thinking. Rather than adding and removing, I encourage you to think in terms of joining (akin to SQL outer-joining) and filtration, which are more functional concepts. In this interpretation, your "local" collection is on the left-hand side of a left outer join, and your "remote" collection is on the right. This reduces the number of iterations from your six down to two, and produces the same output:

Customer.java

package com.stackexchange.ConsentExample;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public record Customer(
    Long id,
    String name,
    Integer consent
) {
    @Override
    public String toString() {
        return String.format(
            "Customer{id=%d, name='%s', consent=%d}",
            id, name, consent);
    }

    public static Stream<Customer> join(
        Collection<Customer> locals,
        Collection<Customer> remotes
    ) {
        /* Take local consent if there is no matching remote consent.
           Take remote consent if there is a match. */
        Map<Integer, Customer> remoteByConsent =
            remotes.stream()
            .collect(Collectors.toMap(
                Customer::consent, Function.identity()
            ));

        return locals.stream()
            .map(local ->
                remoteByConsent.getOrDefault(local.consent, local)
            );
    }
}

JoinTest.java

import com.stackexchange.ConsentExample.Customer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class JoinTest {
    @Test
    public void testJoin() {
        final List<Customer>
        remotes = List.of(
            new Customer(10L, "name1", 12),
            new Customer(11L, "name2", 11),
            new Customer(12L, "name3", 14),
            new Customer(13L, "name4", 16)
        ),
        locals = List.of(
            new Customer(1L, "name1", 12),
            new Customer(2L, "name2", 13),
            new Customer(3L, "name3", 14),
            new Customer(4L, "name4", 15)
        );
        Map<Long, Customer> result =
            Customer.join(locals, remotes)
            .collect(Collectors.toMap(
                Customer::id, Function.identity()
            ));

        assertEquals(4, result.size());

        assertEquals("name1", result.get(10L).name());
        assertEquals(12, result.get(10L).consent());
        assertEquals("name2", result.get(2L).name());
        assertEquals(13, result.get(2L).consent());
        assertEquals("name3", result.get(12L).name());
        assertEquals(14, result.get(12L).consent());
        assertEquals("name4", result.get(4L).name());
        assertEquals(15, result.get(4L).consent());
    }
}
🌐
Javaprogramto
javaprogramto.com › 2020 › 04 › how-to-compare-two-arraylist-for-equality-in-java.html
How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?
June 13, 2021 - ... In this article, We'll learn how to compare two ArrayLists for checking Objects equality. ArrayList has an equal() method that takes one argument type of Object. This equals() method compares the passed list object with the current list object.