user1234
user1234

Reputation: 155

Compare two ArrayList in a two way comparison?

I have a class called Task which I cannot touch because it's a legacy code and I have two ArrayList made up of Task class which I need to compare. Items can be in any order or there can be duplicates as well in the ArrayList.

What is the best way to compare two ArrayList which has object in it and print out the missing elements as well which are not present in either of the list. Is below code is the right and efficient way to do it? I cannot use any external library for this.

I need to compare my two array list in a two way comparison.

Below is my code:

  public static boolean compare(List<Task> source, List<Task> actual) {
    List<Task> matchedTasksList = new ArrayList<Task>();
    List<Task> differedTasksList = new ArrayList<Task>();

    List<Task> copyOfSource = new ArrayList<>(source);
    List<Task> copyOfActual = new ArrayList<>(actual);
    for (Task o : actual) {
      if (!copyOfSource.remove(o)) {
        differedTasksList.add(o);
        System.out.println("Task not present: " + o.toString());
        return false;
      } else {
        matchedTasksList.add(o);
      }
    }
    matchedTasksList.clear();
    for (Task o : source) {
      if (!copyOfActual.remove(o)) {
        differedTasksList.add(o);
        System.out.println("Task not present: " + o.toString());
        return false;
      } else {
        matchedTasksList.add(o);
      }
    }
    return (differedTasksList.size() == 0) ? true : false;
  }

Upvotes: 0

Views: 671

Answers (2)

toongeorges
toongeorges

Reputation: 1976

public boolean compare(List<Task> source, List<Task> actual) {
    Set<Task> intersection = new HashSet<>(source);
    Set<Task> sourceDifference = new HashSet<>(source);
    Set<Task> actualDifference = new HashSet<>(actual);

    intersection.retainAll(actualDifference);

    sourceDifference.removeAll(intersection);
    for (Task t: sourceDifference) {
        System.out.println(String.format("Task %s not present in actual", t));
    }

    actualDifference.removeAll(intersection);
    for (Task t: actualDifference) {
        System.out.println(String.format("Task %s not present in source", t));
    }

    return sourceDifference.isEmpty() && actualDifference.isEmpty();
}

Upvotes: 2

Dilshod Shaymanov
Dilshod Shaymanov

Reputation: 71

it seems like that function only prints first missing element, but as I understood you need to print all missing elements and return false? if so try in this way:

public boolean compare(List<Task> source, List<Task> actual) {
       List<Task> copyOfSource = new ArrayList<>(source);
       copyOfSource.removeAll(actual);
       copyOfSource.forEach(o -> System.out.println("Task not present:    "+o.toString()));
       return copyOfSource.isEmpty();
  }

Upvotes: 0

Related Questions