You are right in saying that if they are arrays you can't use Arrays.equals(), if they are List<>s then you cannot just use equals. In both cases they also check order.

So yes your main option without writing your own comparison algorithm is to use Collections.sort() on both lists.

If you don't need to check for duplicates you could drop both lists into a HashSet using addAll and then compare the two HashSet or just use List.containsAll. The bad news though is that these would both have the same limitation, if you need to compare lists that might have repeated elements then it may give incorrect results. i.e. "bob", "bob", "fred" would compare as equal to "bob", "fred", "fred".

Answer from Tim B on Stack Overflow
๐ŸŒ
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 - A Java Stream can be used for performing sequential operations on data from collections, which includes filtering the differences between lists: List<String> differences = listOne.stream() .filter(element -> !listTwo.contains(element)) .collect(Collectors.toList()); assertEquals(2, differences.size()); assertThat(differences).containsExactly("Tom", "John"); As in our first example, we can switch the order of lists to find the different elements from the second list: List<String> differences = listTwo.stream() .filter(element -> !listOne.contains(element)) .collect(Collectors.toList()); assertEquals(3, differences.size()); assertThat(differences).containsExactly("Daniel", "Alan", "George"); We should note that the repeated calling of List.contains() can be a costly operation for larger lists.
๐ŸŒ
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 - List<String> listOfAdditionalItems = (List<String>) CollectionUtils.removeAll(listOne, listTwo); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("c", "d"), listOfAdditionalItems)); To get the missing elements in list 1, which are present in list 2, we can reverse the solutions in the previous section.
๐ŸŒ
DevQA
devqa.io โ€บ java-compare-two-arraylists
Java Compare Two Lists
March 17, 2020 - 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); } }
๐ŸŒ
W3Docs
w3docs.com โ€บ java
Java Compare Two Lists
Here is an example of how to compare ... = Arrays.asList("a", "b", "c"); if (list1.equals(list2)) { System.out.println("Lists are equal"); } else { System.out.println("Lists are not equal"); }...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 58358599 โ€บ how-to-compare-two-java-collections-of-lists-of-strings-with-least-code
How to compare two java collections of lists of strings with least code? - Stack Overflow
If you want to preserve their current order, copy each list into new List objects; this is fast, as the element objects are not copied, only the references to those element objects are copied. I recommend the second option, not the first. Basically, I know how to solve this, I just wondering how this can be done with least code. Just do it. Write the Person class and compareTo & equals & hashCode methods. No issue of "least code", here just comparing fields. Using the new functional features of Java with lambda syntax can shorten the code.
๐ŸŒ
Java Code Geeks
javacodegeeks.com โ€บ home โ€บ core java
Check If Two Lists Are Equal In Java - Java Code Geeks
March 20, 2019 - If both lists are null, weโ€™ll return true. Or else if only one of them points to a null value or the size() of two lists differ, then weโ€™ll return false. If none of those conditions holds true, weโ€™ll first sort the two lists and then compare them:
Find elsewhere
๐ŸŒ
Java by examples
javaquery.com โ€บ 2014 โ€บ 11 โ€บ how-to-compare-two-list-of-string-in.html
Java by examples: How to compare two List of String in Java?
import java.util.ArrayList; import java.util.List; /** * @author javaQuery */ public class CompareTwoListExample { public static void main(String[] args) { /* Create list of String */ List<String> listString1 = new ArrayList<String>(); /* Add element from 0th position */ listString1.add("a"); listString1.add("b"); listString1.add("c"); listString1.add("d"); listString1.add("e"); /* Print list */ System.out.println("Initial List1:\n" + listString1); System.out.println("---------------------------------"); /* Create list of String */ List<String> listString2 = new ArrayList<String>(); /* Add ele
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

๐ŸŒ
Quora
quora.com โ€บ How-can-two-lists-of-objects-be-compared-in-Java
How can two lists of objects be compared in Java? - Quora
Thankfully, the designers of Java had the mental clarity not to repeat the same mistake again, thus when generics were introduced, they picked the only sensible default, which is to make their conversions invariant, i.e., even if String is a subtype of Object, List<String> is not a subtype of List<Object>.
Top answer
1 of 3
2

First of all, the existing solution with a loop is just fine. Simply translating it to a solution that uses streams is not an improvement.

Here's how I would do it. NB: this is not tested.

// Naive version

List<String> nameList1 = Arrays.asList("Bill", "Steve", "Mark");
List<String> nameList2 = Arrays.asList("Steve Jobs", "Mark", "Bill");

List<String> matchList = nameList1.stream()
    .filter(nameList2::contains)
    .limit(1)
    .collect(Collectors.toList());

count = matchList.size();

Note that there is no need to both append to a list and increment a count.

If you were going to try to parallelize this, then streams could help, but you would need to do it differently.

Finally, if you are really concerned about performance, and nameList2.size() == N is large enough, it will be faster to convert nameList2 to a HashSet. This turns this from an O(MN) algorithm to an O(M) algorithm.

(By contrast, parallelizing the naive version only gives you O(MN/P) complexity at best where P is the number of processes. And that is making some assumptions, and ignoring potential memory contention effects.)

2 of 3
0

tl;dr

If you just want a count of one or zero, for a first match found or no match found, make a stream from the first list, filter with a predicate testing if the second list contains each streamed item from the first list, limit to the first match found, and returning via a ternary statement either number 1 or 0.

int count = 
        List.of( "Bill" , "Steve" , "Mark" )
        .stream()
        .filter( ( String s ) -> List.of( "Steve Jobs" , "Mark" , "Bill" ).contains( s ) )
        .findFirst()
        .isPresent() 
        ? 1 : 0 
;

Not that I recommend that one-liner. See below for more practical code. And see the correct Answer by Stephen C for a variation on this theme.

Details

Given two lists of String objects:

List < String > these = List.of( "Bill" , "Steve" , "Mark" );
List < String > those = List.of( "Steve Jobs" , "Mark" , "Bill" );

List of matches

You can get a List of the items that match.

List < String > matches = these.stream().filter( s -> those.contains( s ) ).collect( Collectors.toList() );

Single match

But you apparently are asking for only the first item that happens to match.

If that is your goal, you use of a List for the result, as well as the counter make no sense. You can only ever have one or zero objects as a result.

Optional

None of the items may match, so we might not get an item back. For this purpose the Optional class was invented, to cover the case of returning either a single object or no object (null). The Optional class protects against a NullPointerException from bungled handling of a return value that is NULL.

Optional < String > match =                   // `Optional` is a class wrapping another object, the payload, which may be NULL. 
    these
    .stream()                                 // Produce a stream of items from this `List`.
    .filter(                                  // Apply a predicate test against each item produced in the stream. Items that pass the test are fed into a new second stream.
        ( String s ) -> those.contains( s )   // Predicate.
    )                                         // Returns another `Stream`.
    .findFirst()                              // Halts the new (second) stream after producing the first item. Returns an `Optional` object, a wrapper around the payload which may be NULL.
;

You can ask the Optional object if it contains a String object or if it is empty. If not you can ask for an alternate value to use as a default. You could throw an NoSuchElementException if you expect there always to be a match. Or you can perform your own logic in case of an empty Optional. See the class doc and search Stack Overflow to learn more about Optional.

if( match.isPresent() ) {
    System.out.println( "Match found: " + match.get() ) ;
}

Dump to console.

System.out.println( "these = " + these );
System.out.println( "those = " + those );
System.out.println( "matches = " + matches );
System.out.println( "match = " + match );

these = [Bill, Steve, Mark]

those = [Steve Jobs, Mark, Bill]

matches = [Bill, Mark]

match = Optional[Bill]

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ list-equals-method-in-java-with-examples
List equals() Method in Java with Examples - GeeksforGeeks
January 3, 2025 - // Java code to show the implementation of // addAll method in list interface import java.util.*; public class Geeks { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing another list List<Integer> l2 = new ArrayList<Integer>(); l2.add(100); l2.add(200); l2.add(300); System.out.println(l2); if (l.equals(l2)) System.out.println("Equal"); else System.out.println("Not equal"); } } ... Program 2: The Case where values are equal. ... // Java cod
๐ŸŒ
Rosetta Code
rosettacode.org โ€บ wiki โ€บ Compare_a_list_of_strings
Compare a list of strings - Rosetta Code
3 weeks ago - # test for all identical procedure allequal(L) if *L >= 2 & !L ~== L[1] then fail else return end # test for strictly ascending procedure ascending(L) if *L >= 2 & i := 1 to *L-1 & L[i] >>= L[i+1] then fail else return end ยท Being one-liners in the form of an if expression they could just as easily be inlined in the main program. For example ... Notes: asc indicates whether y is monotonically increasing, but not necessarily strictly monotonically increasing (in other words, it allows equal elements if they are adjacent to each other). This is a fairly basic procedure in Java, using for-loops, String.equals, and String.compareTo.