Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Saturday, November 16, 2019

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

No comments:

Post a Comment

Please do not add any spam links in the comments section.