$show=/label

Java Program To Find Unmatched values From Two Lists

SHARE:

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


Input:

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"]

Output:

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.

list1.removeAll(list2);

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.
 @Override
 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.

list1.removeAll(list2);

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.


@Override
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:
            eliminated.append(x)
        else:
            pass
    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.

COMMENTS

BLOGGER

About Us

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

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,73,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,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,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Program To Find Unmatched values From Two Lists
Java Program To Find Unmatched values From Two Lists
https://1.bp.blogspot.com/-Y0wxGze9yb8/XN0Stfd9okI/AAAAAAAABgs/DCNz-OoGBNgbUoXX0fbun6sj0XXDs-e0wCLcBGAs/s400/Find%2BUnmatched%2Bvalues%2BFrom%2BTwo%2BLists.PNG
https://1.bp.blogspot.com/-Y0wxGze9yb8/XN0Stfd9okI/AAAAAAAABgs/DCNz-OoGBNgbUoXX0fbun6sj0XXDs-e0wCLcBGAs/s72-c/Find%2BUnmatched%2Bvalues%2BFrom%2BTwo%2BLists.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/find-unmatched-values-from-two-lists.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/find-unmatched-values-from-two-lists.html
true
3124782013468838591
UTF-8
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