Just implement the method that iterates, and reuse it every time you need it:

public static <T> boolean areEqualIgnoringOrder(List<T> list1, List<T> list2, Comparator<? super T> comparator) {

    // if not the same size, lists are not equal
    if (list1.size() != list2.size()) {
        return false;
    }

    // create sorted copies to avoid modifying the original lists
    List<T> copy1 = new ArrayList<>(list1);
    List<T> copy2 = new ArrayList<>(list2);

    Collections.sort(copy1, comparator);
    Collections.sort(copy2, comparator);

    // iterate through the elements and compare them one by one using
    // the provided comparator.
    Iterator<T> it1 = copy1.iterator();
    Iterator<T> it2 = copy2.iterator();
    while (it1.hasNext()) {
        T t1 = it1.next();
        T t2 = it2.next();
        if (comparator.compare(t1, t2) != 0) {
            // as soon as a difference is found, stop looping
            return false;
        }
    }
    return true;
}
Answer from JB Nizet on Stack Overflow
๐ŸŒ
Medium
medium.com โ€บ @QA-initi โ€บ how-to-compare-two-array-list-in-java-using-comparator-cc05617175b5
How to compare two array list in Java using Comparator | by QA-init | Medium
November 14, 2023 - ArrayList<Integer> list1 = new ... list2.add(1); Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }; Collections.sort(list1, comparator); ...
๐ŸŒ
HappyCoders
happycoders.eu โ€บ home โ€บ java โ€บ compareto, comparable, comparator โ€“ comparing objects in java
compareTo, Comparable, Comparator โ€“ Compare Objects in Java
1 month ago - The Javadoc calls this value the so-called sort key and the parameter of comparing() accordingly keyExtractor โ€“ the term comes up again below with the null values. ... This notation makes it easy for us to also cover the scenario where two students have the same last name and the same first name.
Discussions

Java Comparator - Comparing 2 different objects in list - Stack Overflow
I have following class in Java, and I want to compare the tocompare objects in list with the previous tocompare object i.e compare t2 to t1. I am new to Java, so I don't have much knowledge abou... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Comparing two Arraylists
If you would like to compare the items of two lists. You can create a loop and then you can compare each item step by step. If you would like to compare two lists independently from each other. You can use Java Comparator class with sort function. You can define code logic which has sorting rules. With this way, you can compare the fields of class whatever you want. I hope this is your expected answer ? More on reddit.com
๐ŸŒ r/javahelp
5
3
January 25, 2018
Java Compare Two List's object values? - Stack Overflow
I have two list **ListA listA = new ArrayList ()** and ListB listB = new ArrayList () both contain object of type MyData and MyData contain these More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
Top answer
1 of 2
10

Just implement the method that iterates, and reuse it every time you need it:

public static <T> boolean areEqualIgnoringOrder(List<T> list1, List<T> list2, Comparator<? super T> comparator) {

    // if not the same size, lists are not equal
    if (list1.size() != list2.size()) {
        return false;
    }

    // create sorted copies to avoid modifying the original lists
    List<T> copy1 = new ArrayList<>(list1);
    List<T> copy2 = new ArrayList<>(list2);

    Collections.sort(copy1, comparator);
    Collections.sort(copy2, comparator);

    // iterate through the elements and compare them one by one using
    // the provided comparator.
    Iterator<T> it1 = copy1.iterator();
    Iterator<T> it2 = copy2.iterator();
    while (it1.hasNext()) {
        T t1 = it1.next();
        T t2 = it2.next();
        if (comparator.compare(t1, t2) != 0) {
            // as soon as a difference is found, stop looping
            return false;
        }
    }
    return true;
}
2 of 2
4

Here's a Java 8 way of solving your problem. First make sure the lists are of equal length:

List<SystemUserWithNameAndId> list1 = ... ;
List<SystemUserWithNameAndId> list2 = ... ;

if (list1.size() != list2.size()) {
    return false;
}

Now build a Comparator using the new comparator utilities. The idea is that instead of writing custom logic for a comparator, most comparators do something like comparing two objects by extracting a key from them, and then comparing the keys. That's what this does.

Comparator<SystemUserWithNameAndId> comp =
    Comparator.comparingInt(SystemUserWithNameAndId::getSystemUserId);

Sort the lists. Of course, you might want to make copies before sorting if you don't want your function to have the side effect of sorting its input. If your input lists aren't random access (who uses LinkedList nowadays?) you might also want to copy them to ArrayLists to facilitate random access.

list1.sort(comp);
list2.sort(comp);

Run a stream over the indexes of the lists, calling the comparator on each pair. The comparator returns 0 if the elements are equals according to this comparator. If this is true for all pairs of elements, the lists are equal.

return IntStream.range(0, list1.size())
    .allMatch(i -> comp.compare(list1.get(i), list2.get(i)) == 0);
๐ŸŒ
ZetCode
zetcode.com โ€บ java โ€บ comparablecomparator
Java Comparable Comparator - comparing objects with Comparable and Comparator
Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering. The following two lists summarize the differences between the two interfaces. ... Java language offers some built-int Comparators.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 48811269 โ€บ java-comparator-comparing-2-different-objects-in-list
Java Comparator - Comparing 2 different objects in list - Stack Overflow
public class ToCompare { private String property1; private String property2; public void getProperty1(){ return property1; } public void setProperty1(String property1){ this.property1 = property1; } public void getProperty2(){ return property2; } public void setProperty1(String property2){ this.property2 = property2; } } List<ToCompare> tocompare = new ArrayList(); ToCompare t1 = new ToCompare(); ToCompare t2 = new ToCompare(); ToCompare t3 = new ToCompare(); ToCompare t4 = new ToCompare(); tocompare.add(t1); //obj1 tocompare.add(t2); //obj2 tocompare.add(t3); //obj3 tocompare.add(t4); //obj4
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ javas-objects-compare-method-explained-7a9ccda5ea74
Javaโ€™s Objects.compare() Method Explained | Medium
December 13, 2024 - However, other approaches can achieve similar results depending on the requirements of the code. The Comparator interface provides a compare() method that can be directly used to compare two objects.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-compare-objects-with-custom-comparator-in-java-419620
How to compare objects with custom comparator in Java | LabEx
In Java, a Comparator is an interface that allows you to define custom comparison logic for objects. It provides a way to compare two objects and determine their order, which is particularly useful when you want to sort collections or implement custom sorting mechanisms.
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @leninstalinesec โ€บ how-to-comparing-two-java-objects-5344f3d0fbc
How to Comparing two java objects | by lenin stalin | Medium
May 11, 2019 - More get with Java collection example ... class NameComparator implements Comparator<Person> { @Override public int compare(Person o1, Person o2) { return o1.name.compareTo(o2.name); } }class AgeComparator implements Comparator<Person> { @Override public int compare(Person o1, Person o2) { return ((Integer)o1.age).compareTo(o2.age); } } Now we can specify one of the above-defined sorting function to choose sorting on demand: ... List<Person> students = Arrays.asList( new Person(20,"Bob"), new Person(19, "Jane"), new Person(21,"Foo") ); Collections.sort(students, new AgeComparator());
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
The Comparator interface allows you to create a class with a compare() method that compares two objects to decide which one should go first in a list.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 404400 โ€บ java โ€บ compare-objects-comparator
How to compare to objects using comparator? (Beginning Java forum at Coderanch)
FooComparator fc = ... if (fc.compare(aFoo, anotherFoo) > 0) ... The main reason Comparator is especially useful is that there is often more than one way to compare instances of a single class: you might sort Person objects by name, by address, by age... so you can define a NameComparator, an AddressComparator, and an AgeComparator. If you have Person implement Comparable, then you can only do it one way. A lot of the Java Collections classes let you supply a Comparator to tell the collection how to sort the objects you put into the collection.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ collections framework โ€บ java arraylist โ€บ compare two lists in java: equality, differences, common items
How to Compare Two Lists in Java
1 week ago - 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.
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ -efficiently-compare-two-lists-objects-java
How to Efficiently Compare Two Lists of Objects in Java? - CodingTechRoom
Comparing two lists of objects in Java can be achieved through various techniques, depending on the desired outcome, such as equality check, content comparison, or structural comparison. Below are the common approaches. ... // Using Java Streams for unordered list comparison boolean areContentEqual = list1.size() == list2.size() && list2.containsAll(list1); ... Use List.equals(Object obj) method for simple equality checks if order matters.
๐ŸŒ
DevQA
devqa.io โ€บ java-compare-two-arraylists
Java Compare Two Lists
March 17, 2020 - The List interface in Java provides methods to be able to compare two Lists and find the common and missing items from the lists.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java classes โ€บ java comparator and comparable
Java Comparator and Comparable
January 14, 2025 - We need to implement only one interface method: compare(). It takes two Car objects as inputs and compares their maximum speeds in the usual way (by subtraction). Like compareTo(), it returns an int, and the principle of comparison is the same. How do we use this? It's all straightforward: import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Main { public static void main(String[] args) { List<Car> cars = new ArrayList<>(); Car ferrari = new Car(1990, "Ferrari 360 Spider", 310); Car lambo = new Car(2012, "Lamborghini Gallardo", 290); Car bugatti = new Car(2010, "Bugatti Veyron", 350); cars.add(ferrari); cars.add(bugatti); cars.add(lambo); Comparator speedComparator = new MaxSpeedCarComparator(); Collections.sort(cars, speedComparator); System.out.println(cars); } } Console output:
๐ŸŒ
Medium
medium.com โ€บ @thecodebean โ€บ java-object-sorting-explained-using-comparable-and-comparator-03b93b988f75
Java Object Sorting Using Comparable and Comparator | The Code Bean | Medium
October 21, 2023 - The compare method in a Comparator takes two objects as arguments and returns a negative integer, zero, or a positive integer based on the comparison result. You can use Comparator instances to sort objects, search for specific objects in a ...
๐ŸŒ
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.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-compare-java-objects-based-on-multiple-attributes-417392
How to compare Java objects based on multiple attributes | LabEx
The Comparator<T> interface defines a method compare(T o1, T o2) that compares two objects of the same type. Unlike Comparable, which is implemented by the class being compared, a Comparator is a separate class or lambda expression that can ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-comparator-interface
Java Comparator Interface - GeeksforGeeks
Uses Comparator (lambda expression) to sort students by id. Collections.sort() applies the custom sorting logic. Output is sorted in ascending order of id. compare(T o1, T o2): Compares two objects for order.
Published: May 13, 2026