Java Program To Find Unmatched values From Two Lists


1. Overview: In this tutorial, We'll be learning about a java program how to compare two lists and find out the unmatched contents f...

1. Overview:

In this tutorial, We'll be learning about a java program how to compare two lists and find out the unmatched contents from those two lists. We will demonstrate the example programs in Java and Python languages.

1.1 Example


List 1: ["File Name 1", "File Name 2", "File Name 3", "File Name 4", "File Name 5", "File Name 6", "File Name 7", "File Name 8"]
List 2: ["File Name 2", "File Name 4", "File Name 6", "File Name 8"]


Unmatched values: ["File Name 1", "File Name 3", "File Name 5", "File Name 7]

Find Unmatched values From Two Lists

This example is for Strings. If the list is having custom objects such as objects of Student, Trade or CashFlow. But in our tutorial, We will discuss for Employee objects in the list.

We can use any List implementation classes such as ArrayList, LinkedList, Stack, and Vector. For now, all programs in this post are using ArrayList implementation.

2. Java

We'll write a program to remove the duplicates values from list1 based on list2 and operation seems to be more complex but if we use the java collection API methods then our life will become easy because these methods are being tested by many developers every day.

See in our case need to find the unmatched content against list2 from list1.

2.1 String values

List interface has a method named "removeAll" which takes any collection implementation class (in our example it an ArrayList).

removeAll() method removes from the current list all of its elements that are contained in the specified collection that passed to this method as an argument.

Syntax: See the method signature below.

boolean removeAll(Collection c)

Creating two lists which are having files names in it.

// List 1 contains file names from 1 to 8.
List list1 = new ArrayList<>();
list1.add("File Name 1");
list1.add("File Name 2");
list1.add("File Name 3");
list1.add("File Name 4");
list1.add("File Name 5");
list1.add("File Name 6");
list1.add("File Name 7");
list1.add("File Name 8");

//List 2 contains only even number file names.
List list2 = new ArrayList<>();
list2.add("File Name 2");
list2.add("File Name 4");
list2.add("File Name 6");
list2.add("File Name 8");

Now we are going to delete the file names that are already present in list 2 from list 1.


All the elements that are present in list2 are deleted from list1 which means all even number file names are deleted from list1.

Let us take a look at the contents in list1.

[File Name 1, File Name 3, File Name 5, File Name 7]

Note: If list2 is null then will through NullPointerException.

2.2 Custom Objects

What happens if these two lists are having objects instead of String literals? Custom objects such as Employee, Student, Trade or User objects.

We will demonstrate an example with Employee object for now. The same is applicable for any type of object in the list.

Creating an Employee class with id and name.

public class Employee {

 private int id;
 private String name;

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;

 // setter and getter methods.
 // Overrding toString method.
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";

Creating list1 and list2 with employee objects.

List list1 = new ArrayList<>();
list1.add(new Employee(100, "Jhon"));
list1.add(new Employee(200, "Cena"));
list1.add(new Employee(300, "Rock"));
list1.add(new Employee(400, "Undertaker"));

List list2 = new ArrayList<>();
list2.add(new Employee(100, "Jhon"));
list2.add(new Employee(300, "Rock"));

list1 and list2 have common employee objects for id 100 and 200 with the same name. Now we have to remove these two objects from list1. We know that removeAll method removes objects from list1 comparing with list2 objects. We'll call removeAll method.


Now see the objects in list1 after calling removeAll method.

[Employee [id=100, name=Jhon], Employee [id=200, name=Cena], Employee [id=300, name=Rock], Employee [id=400, name=Undertaker]]

Observe that removeAll method is not removed duplicate objects from list1.
To make this code work, we need to override equals() method in Employee class as below.

public boolean equals(Object obj) {
 Employee other = (Employee) obj;
 if (id != other.id)
  return false;
 if (name == null) {
  if (other.name != null)
   return false;
 } else if (!name.equals(other.name))
  return false;
 return true;

Why we need to override equals method is because removeAll method internally compares the contents invoking equals() method on each object. Here the object is an employee so it calls equals method on employee object.

Take a look at the output of list1 now.

[File Name 1, File Name 3, File Name 5, File Name 7]

We have to notice one point here that the same code had worked in the case of String objects because String class already overridden equals method as below.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    if (anObject instanceof String) {
        String aString = (String)anObject;
        if (coder() == aString.coder()) {
            return isLatin1() ? StringLatin1.equals(value, aString.value)
                              : StringUTF16.equals(value, aString.value);
    return false;

All codes are shown are compiled and run successfully in java 12.

3. Python

In Python, finding out the unmatched contents from two lists is very simple in writing a program.

Let us have a look at the following code.

def finder(arr1,arr2):
    eliminated = []

    for x in arr1:
        if x not in arr2:
    return eliminated

We can sort two lists before for loop as below. I have seen many developers do sorting before comparing the contents. But, actually sorting is not necessary to do.

arr1 = sorted(arr1)
arr2 = sorted(arr2)

4. Conclusion

In this tutorial, We've explored the way to remove the duplicate contents from list 1 against list 2 and finding out the unmatched contents from two lists.

Further discussed comparing two employee lists and finding out unmatched content using removeAll method in Java and Program in Python for the same.

As usual, All examples are shown in this tutorial are available on GitHub.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java Program To Find Unmatched values From Two Lists
Java Program To Find Unmatched values From Two Lists
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content