簡體   English   中英

用兩種方式比較兩個ArrayList嗎?

[英]Compare two ArrayList in a two way comparison?

我有一個稱為Task的類,因為它是一個遺留代碼,所以我無法觸摸,並且我有兩個由Task類組成的ArrayList需要比較。 項可以按任何順序排列,或者ArrayList中也可以有重復項。

比較其中有對象的兩個ArrayList並打印出兩個列表中都不存在的缺少元素的最佳方法是什么? 下面的代碼是正確而有效的方法嗎? 我不能為此使用任何外部庫。

我需要通過兩種方式比較兩個數組列表。

  • 如果數據是源數據,而不是實際數據,則返回false並打印出丟失的元素。
  • 如果數據是實際數據,而不是源數據,則也返回false並打印出丟失的元素。

下面是我的代碼:

  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;
  }
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();
}

似乎該功能僅打印第一個丟失的元素,但是據我了解,您需要打印所有丟失的元素並返回false? 如果是這樣,請嘗試這種方式:

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();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM