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
🌐
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
June 1, 2018 - Comparing each element of a List against some condition. 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.
Discussions

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
java - Comparing a list of objects - Stack Overflow
I have a program that represents a deck of cards using an ArrayList and I want to compare two decks to see if they are equal (have the same size, same cards, and in the same order). I know you can do More on stackoverflow.com
🌐 stackoverflow.com
Best way to compare Two Lists of Objects in Java - Stack Overflow
I have two lists of Objects. public class CustomObj { Long key1; Integer key2; Integer key3; Integer key4; Integer key5; BigDecimal value1 BigDecimal value2 BigDec... More on stackoverflow.com
🌐 stackoverflow.com
August 12, 2016
Best way to compare two lists of objects
I am trying to figure out the most efficient way (lowest execution time) to filter two lists of objects, keeping only a sublist of list A whose objects are not in list B. One list is coming form an external API and the other list is coming from my Backendless DB. More on support.backendless.com
🌐 support.backendless.com
1
0
January 8, 2022
🌐
Quora
quora.com › How-can-two-lists-of-objects-be-compared-in-Java
How can two lists of objects be compared in Java? - Quora
So you gotta override the `equals()` and `hashCode()` methods in your object class . This is super important , otherwise , Java's just gonna do a shallow comparison, which is almo ...
🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
October 10, 2025 - However, that’s deprecated since Java 7, when Objects#equals appeared · Now let’s compare object order with the ObjectUtils#compare method. It’s a generic method that takes two Comparable arguments of that generic type and returns an Integer.
🌐
Baeldung
baeldung.com › home › java › java list › finding the differences between two lists in java
Finding the Differences Between Two Lists in Java | Baeldung
January 28, 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.
🌐
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.
🌐
Stack Overflow
stackoverflow.com › questions › 23254319 › comparing-a-list-of-objects
java - Comparing a list of objects - Stack Overflow
The List interface doesn't have the compareTo method. ... if you see the implementation of the equals on the ArrayList (actually AbstractList), you see that iterates on both list and try to the equals the elements. ... According to implementation of Abstract List's equals methos the super class of ArrayList which can be found here ... @Override public boolean equals(Object other){ if(this == other) return true; if(other == null || (this.getClass() != other.getClass())){ return false; } Card otherCard = (Card) other; return (this.value == otherCard.value) && (this.color == otherCard.color); }
Find elsewhere
🌐
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 - Feel free to reference my mock ... versus java calculating it). It's impossible to check for changes since there is no unique key that can be compared across the two connectors. The difference function's purpose is not to find the changed objects, it's only for finding the added/removed ones. The changed objects are found by creating the two new lists and then comparing their contents; that was the point of creating copies ...
🌐
Backendless
support.backendless.com › server code › codeless
Best way to compare two lists of objects - Codeless - Backendless Support
January 8, 2022 - I am trying to figure out the most efficient way (lowest execution time) to filter two lists of objects, keeping only a sublist of list A whose objects are not in list B. One list is coming form an external API and the …
🌐
Medium
medium.com › @AlexanderObregon › javas-objects-compare-method-explained-7a9ccda5ea74
Java’s Objects.compare() Method Explained | Medium
December 13, 2024 - Sorting collections of objects that may include null values is another common use case. Using Objects.compare() within a custom comparator allows you to sort the list while keeping nulls in a defined position, such as at the beginning or the end.
🌐
Medium
donraab.medium.com › comparing-collections-in-java-69c7e70fc5f1
Comparing Collections in Java - Donald Raab - Medium
May 2, 2024 - When these methods fail, they provide useful messages explaining what the difference is between the two objects being compared based on their toString result. These two Assertions are very useful when it comes to comparing two Collections in Java. Developers who use the Java Collection Framework have three basic Collection types that they can use to compare for equality. These types are java.util.List, java.util.Set, and java.util.Map. In Eclipse Collections, there is a fourth type named Bag. A Collection is equal to another Collection of the same type.
🌐
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 = new ArrayList<String>(); listB.add("double"); listB.add("int"); listB.add("float"); 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 using java 8 stream api. Stream API is very powerful but in this case, it is good to use either equals() or containsAll() method which is more comfortable to use for programmers. The below program shows how to compare two ArrayList of different objects in Java 8 using stream api..
🌐
Wikibooks
en.wikibooks.org › wiki › Java_Programming › Comparing_Objects
Comparing Objects - Wikibooks, open books for an open world
In Java, there are several existing ... and want the objects of your class to be sortable, you have to implement the Comparable and redefine the compareTo(Object obj) method....
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;
    }
🌐
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 - Learn to test whether two arraylists are equal and then find different list items. ... Learn to compare two ArrayList in Java to find if they contain equal elements. If both lists are unequal, we will find the difference between the lists.
Top answer
1 of 5
3

The “different member variables” is irrelevant. It’s an implementation detail. What you need is a set of rules which of two people comes first.

You could for example sort by family name, then given name, then date of birth, and if these are all three equal, take the name of the school, university or company (which will be different member variables) and compare them as strings. If that is equal, you might have student and employee ids, and the student ids might be unique, and the employee ids might be unique, but student and employee ids might be the same. So you could sort then students first ordered by id, followed by employees sorted by id, if you might sort by if first if student and employee ids are comparable.

(University or school and employer might be the same, because universities are also employers).

2 of 5
3

Comparing objects with different fields sounds like bad polymorphic design, whether it's Java or any other OOP language:

  • If your comparator needs to know the precise subtype of an object to do the comparison, you mess-up with the the open-closed principle, since for every new subclassing, you'd potentially need to modify the comparator to select the relevant fields.
  • If your comparator needs uses reflexion to find on its own the relevant fields to compare, you indirectly mess up with the principle of encapsulation, since you create a hidden requirement that information to be compared must be in some predetermined field.

If you want to sort People properly in a clean polymorphic design:

  • you need to rely either on a field, available for any kind of People, including Student, or
  • you may call some function/transformation that provides a unique value (e.g. a string) that allows to sort any People. People and Student may then just use a different transformation that will be passed to the comparator; Or
  • you only sort among homogeneous subtypes.
🌐
Coderanch
coderanch.com › t › 673893 › java › Comparing-ArrayLists-objects-shared-properties
Comparing two ArrayLists containing different objects with (some) shared properties (Beginning Java forum at Coderanch)
December 15, 2016 - For comparing sorted lists you need two indexes, one for users and one for messages. ... JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
Top answer
1 of 12
182

EDIT

Here are two versions. One using ArrayList and other using HashSet

Compare them and create your own version from this, until you get what you need.

This should be enough to cover the:

P.S: It is not a school assignment :) So if you just guide me it will be enough

part of your question.

continuing with the original answer:

You may use a java.util.Collection and/or java.util.ArrayList for that.

The retainAll method does the following:

Retains only the elements in this collection that are contained in the specified collection

see this sample:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;

public class Repeated {
    public static void main( String  [] args ) {
        Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
        Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));

        listOne.retainAll( listTwo );
        System.out.println( listOne );
    }
}

EDIT

For the second part ( similar values ) you may use the removeAll method:

Removes all of this collection's elements that are also contained in the specified collection.

This second version gives you also the similar values and handles repeated ( by discarding them).

This time the Collection could be a Set instead of a List ( the difference is, the Set doesn't allow repeated values )

import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;

class Repeated {
      public static void main( String  [] args ) {

          Collection<String> listOne = Arrays.asList("milan","iga",
                                                    "dingo","iga",
                                                    "elpha","iga",
                                                    "hafil","iga",
                                                    "meat","iga", 
                                                    "neeta.peeta","iga");

          Collection<String> listTwo = Arrays.asList("hafil",
                                                     "iga",
                                                     "binga", 
                                                     "mike", 
                                                     "dingo","dingo","dingo");

          Collection<String> similar = new HashSet<String>( listOne );
          Collection<String> different = new HashSet<String>();
          different.addAll( listOne );
          different.addAll( listTwo );

          similar.retainAll( listTwo );
          different.removeAll( similar );

          System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
      }
}

Output:

$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]

Two:[hafil, iga, binga, mike, dingo, dingo, dingo]

Similar:[dingo, iga, hafil]

Different:[mike, binga, milan, meat, elpha, neeta.peeta]

If it doesn't do exactly what you need, it gives you a good start so you can handle from here.

Question for the reader: How would you include all the repeated values?

2 of 12
45

You can try intersection() and subtract() methods from CollectionUtils.

intersection() method gives you a collection containing common elements and the subtract() method gives you all the uncommon ones.

They should also take care of similar elements