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
🌐
Quora
quora.com › How-can-two-lists-of-objects-be-compared-in-Java
How can two lists of objects be compared in Java? - Quora
Answer (1 of 4): A̲l̲r̲i̲g̲h̲t̲ ̲,̲ ̲s̲o̲ ̲y̲o̲u̲ ̲w̲a̲n̲n̲a̲ ̲c̲o̲m̲p̲ar̲e̲ ̲t̲w̲o̲ ̲l̲is̲t̲s̲ ̲o̲f̲ ̲o̲b̲j̲e̲c̲t̲s ̲i̲n̲ ̲J̲a̲v̲a̲—̲f̲i̲r̲s̲t̲ ̲t̲h̲i̲n̲g̲ ̲t̲o̲ ̲c̲h̲e̲c̲k̲ ̲i̲s̲ ̲i̲f̲ ̲t̲h̲e̲y̲’̲r̲e̲ ...
Discussions

Comparing two list of objects in Java - Stack Overflow
I have two list of Student Objects(listA & listB) which were formed by querying from two different databases. I need to iterate one list and need to make sure it is not present in the other lis... More on stackoverflow.com
🌐 stackoverflow.com
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 same, but may have identical field values. It is those values that I need to compare. Currently, I am using Java ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 21, 2018
How can I compare two lists of objects of the same size
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. More on reddit.com
🌐 r/javahelp
6
2
October 4, 2023
comparator - Compare two List of Objects in Java - Stack Overflow
I need some help with an issue I'm facing when comparing two lists of objects (TestFoo type). The goal is to check both list is equals or not The Goal: I need to compare existingItems and newItems ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Coderanch
coderanch.com › t › 638779 › java › Compare-Contrast-ArrayList-Object
Compare and Contrast Two ArrayList<Object> (Java in General forum at Coderanch)
August 29, 2014 - There are 3 pieces of information you eventually want: - Added objects (exist in List 1 but not in List 2). - Removed objects (exist in List 2 but not in List 1). - Changed objects (exist in both lists, but one or more of their fields have changed). The first two are solved with a utility method that can compare two lists and return the difference of them.
🌐
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.
🌐
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 ...
🌐
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? JavaProgramTo.com
June 13, 2021 - // list 2 List<String> listB = ... listB.add("linkedlist"); // comparing two lists boolean isEqualAllValues = listA.containsAll(listB); System.out.println(isEqualAllValues); Output: ... Now, it is time to write the same logic ...
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 \ 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 \ time.

  • Use a hashset: you can find if an element is in the set in constant time, \

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;
    }
🌐
DevQA
devqa.io › java-compare-two-arraylists
Java Compare Two Lists
March 17, 2020 - If you want to check that two lists are equal, i.e. contain the same items and and appear in the same index then we can use: import java.util.Arrays; import java.util.List; public class CompareTwoLists { public static void main(String[] args) { List<String> listOne = Arrays.asList("a", "b", "c"); List<String> listTwo = Arrays.asList("a", "b", "c"); List<String> listThree = Arrays.asList("c", "a", "b"); boolean isEqual = listOne.equals(listTwo); System.out.println(isEqual); isEqual = listOne.equals(listThree); System.out.println(isEqual); } }
🌐
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.
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › how to compare two lists in java
How to Compare Two Lists in Java - HowToDoInJava
September 20, 2023 - The following Java program tests if two given lists are equal. To test equality, we need to sort both lists and compare both lists using equals() method.
🌐
Stack Overflow
stackoverflow.com › questions › 79236063 › compare-two-list-of-objects-in-java
comparator - Compare two List of Objects in Java - Stack Overflow
I need to compare existingItems and newItems (both of type TestFoo) to identify both are contains same contents or not ... Both the existingESItems and newItems are converted into sorted sets (SortedSet). I’m using a comparator to sort these sets based on the uniqueItemDetailId property. After sorting, I compare the sets using .equals(). However, even though the lists contain different values, the comparison (sortedExistingESItems.equals(sortedNewESItems)) is not triggering the if block, and the code isn't behaving as expected.
🌐
Stack Overflow
stackoverflow.com › questions › 25790022 › compare-two-list-objects-in-java
Compare two list objects in java - Stack Overflow
Following code of UserInfo shows methods generated by IntelliJ: public class UserInfo { private int domainId; private String id; private String status; public void setDomainId(int domainId) { this.domainId = domainId; } public void setId(String id) { this.id = id; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserInfo userInfo = (UserInfo) o; if (domainId != userInfo.domainId) return false; if (id != null ?
🌐
amitph
amitph.com › home › java › comparing two lists in java
Comparing Two Lists In Java - amitph
November 22, 2024 - Learn compare, find commonality, and difference in two Java Lists using Plain Java, Java Streams, and Commons Collections library
🌐
Stack Overflow
stackoverflow.com › questions › 59376939 › how-to-compare-two-lists-of-java-objects-by-property-values
testing - How to Compare Two Lists of Java Objects by Property Values - Stack Overflow
December 17, 2019 - By overriding the equal and hash methods for your object,you can use the compare method of your lists as shows in the following sample: this helps you to compare objects by as many as their proprieties as you want. import java.util.*; public class TestListConvert { public static void main(String[] args) { List<Obs> firstList = new ArrayList<>(); List<Obs> secondList = new ArrayList<>(); firstList.add(new Obs("1","2")); secondList.add(new Obs("1","2")); System.out.println(firstList.equals(secondList)); } private static class Obs{ private String x; private String y; public Obs(String x, String y