If I understand correctly, this is the example scenario:

  • listOne [datab] items: [A, B, C, D]
  • listTwo [front] items: [B, C, D, E, F]

and what you need to get as an effect is:

  • added: [E, F]
  • deleted: [A]

First thing first, I would use some type adapter or extend the different types from one common class and override the equals method so you can match them by id and name

Secondly, this is very easy operations on sets (you could use set's but list are fine too). I recommend using a library: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html

And now basically:

  • added is listTwo - listOne
  • deleted is listOne - listTwo

and using java code:

  • added: CollectionUtils.removeAll(listTwo, listOne)
  • deleted: CollectionUtils.removeAll(listOne, listTwo)

Otherwise, all collections implementing Collection (Java Docs) also has removeAll method, which you can use.

Answer from Atais 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 - 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.
Top answer
1 of 4
19

If I understand correctly, this is the example scenario:

  • listOne [datab] items: [A, B, C, D]
  • listTwo [front] items: [B, C, D, E, F]

and what you need to get as an effect is:

  • added: [E, F]
  • deleted: [A]

First thing first, I would use some type adapter or extend the different types from one common class and override the equals method so you can match them by id and name

Secondly, this is very easy operations on sets (you could use set's but list are fine too). I recommend using a library: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html

And now basically:

  • added is listTwo - listOne
  • deleted is listOne - listTwo

and using java code:

  • added: CollectionUtils.removeAll(listTwo, listOne)
  • deleted: CollectionUtils.removeAll(listOne, listTwo)

Otherwise, all collections implementing Collection (Java Docs) also has removeAll method, which you can use.

2 of 4
18

I propose solution using java 8 streams:

    ArrayList<ObjOne> list = new ArrayList<>(Arrays.asList(new ObjOne("1","1"),new ObjOne("3","3"),new ObjOne("2","2")));
    ArrayList<ObjTwo> list2 = new ArrayList<>(Arrays.asList(new ObjTwo("1","1"),new ObjTwo("3","3"),new ObjTwo("4","4")));

    List<ObjOne> removed = list.stream().filter(o1 -> list2.stream().noneMatch(o2 -> o2.getId().equals(o1.getId())))
            .collect(Collectors.toList());
    System.out.print("added ");
    removed.forEach(System.out::println);

    List<ObjTwo> added = list2.stream().filter(o1 -> list.stream().noneMatch(o2 -> o2.getId().equals(o1.getId())))
             .collect(Collectors.toList());

    System.out.print("removed ");
    added.forEach(System.out::println);

This is basically your solution but implemented using streams, which will make your code shorter and easer to read

Discussions

An elegant way to find diff of two list of objects in Java - Code Review Stack Exchange
This is the simplest possible implementation. The two lists will contain at max, 3-5 elements, so the size of lists is not a matter of concern. Any recommendation on how can I make this pretty? More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 4, 2012
java - How can I return the difference between two lists? - Stack Overflow
I have two array lists e.g. List a; contains : 10/10/2014, 10/11/2016 List b; contains : 10/10/2016 How can i do a check between list a and b so the value that is missing... More on stackoverflow.com
🌐 stackoverflow.com
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
Java Compare Two Lists - Stack Overflow
I have two lists ( not java lists, you can say two columns) For example **List 1** **Lists 2** milan hafil dingo iga iga dingo ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - Note that the difference between ... are equal. To test equality, we need to sort both lists and compare both lists using equals() method....
🌐
DevQA
devqa.io › java-compare-two-arraylists
Java Compare Two Lists
March 17, 2020 - The List interface also provides methods to find differences between two lists. The removeAll() method compares two lists and removes all the common items. What’s left is the additional or missing items.
🌐
Quora
quora.com › How-can-two-lists-of-objects-be-compared-in-Java
How can two lists of objects be compared in Java? - Quora
Wait a moment and try again.Try again ... Java (programming languag... ... Comparing two lists of objects in Java depends on what “compare” means in your context: equality (same elements, order matters or not), ordering (which list is greater), or set-like differences (which elements added/removed).
🌐
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 ...
🌐
amitph
amitph.com › home › java › finding the difference between two java lists
Finding the Difference Between Two Java Lists - amitph
November 22, 2024 - List<String> differences = new ArrayList<>( CollectionUtils.removeAll(one, two)); System.out.println(differences); //[Tim, Leo, Tim]Code language: Java (java) Similar to our previous two examples, we can change the argument’s order to the removeAll() method to see the differences the other way around. Google Guava is a popular open-source library containing utility methods and abstractions.
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 - 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 and removing the added/removed objects.
🌐
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,
🌐
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 - 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.
🌐
Javaprogramto
javaprogramto.com › 2020 › 04 › how-to-compare-two-arraylist-for-equality-in-java.html
JavaProgramTo.com: How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?
// 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 ...
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

🌐
Google Groups
groups.google.com › g › clojure › c › YYFLB7Z4II8
Get difference between two lists with java objects of same class
March 11, 2013 - I assume this rules out the use of clojure.data/diff and I will need my own function like Marko suggested to make those property comparisons. Yes, from data/diff's perspective you'd have all distinct objects. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... I only asked because if they aren't java.util.Lists to begin with, you'd definitely not want to convert into one just to use removeAll. What if, i had two clojure lists, with hash-maps which have the same keys and based on a specific key, i wanted to find the items from list-a which do not exist in list-b.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparing-two-arraylist-in-java
Comparing two ArrayList In Java - GeeksforGeeks
January 23, 2026 - To compare two ArrayList objects, Java provides the equals() method. This method checks whether both lists have the same size and contain the same elements in the same order, making it a simple and reliable way to compare lists.
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());
    }
}
🌐
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 - It's the semantics and the idea behind the objects that count, not where the data is coming from. Carey is right. It seems you only need the phone numbers to match delivered messages with expected deliveries. The time data will only be used to determine if the delivery was "reasonable timely". If you're using Java 8, then the Map's default interface methods I mentioned earlier should give you a way to easily process the lists.
🌐
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.