【问题标题】:How to find the differences from 2 ArrayLists of Strings?如何找到与 2 个 ArrayLists of Strings 的区别?
【发布时间】:2013-06-04 15:23:31
【问题描述】:

我有 2 个字符串:

A1=[Rettangolo, Quadrilatero, Rombo, Quadrato]
A2=[Rettangolo, Rettangolo, Rombo, Quadrato]

我想得到这个:“我找到了“Quadrilatero”,而不是“Rettangolo””。 如果我使用 removeAll()retainAll() 它不起作用,因为我有 2 个“Rettangolo”实例。 事实上,如果我使用a1.containsAll(a2),我会得到真,我想要假。

感谢大家考虑我的要求。

【问题讨论】:

  • 数组的长度可以不同吗?
  • 您是否希望 A1 中的所有元素都出现在 A2 中,无论顺序如何还是顺序也很重要?
  • 是的,数组大小可以不同。顺序并不重要。

标签: java arraylist array-difference


【解决方案1】:

使用 ArrayList 中的 remove 方法。它只删除第一次出现。

public static void main(String []args){
        //Create ArrayLists
        String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
        ArrayList<String> a1=new ArrayList(Arrays.asList(A1));
        String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
        ArrayList<String> a2=new ArrayList(Arrays.asList(A2));
        // Check ArrayLists
        System.out.println("a1 = " + a1);
        System.out.println("a2 = " + a2);
        // Find difference
        for( String s : a1)
            a2.remove(s);
        // Check difference
        System.out.println("a1 = " + a1);
        System.out.println("a2 = " + a2);
}

结果

a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo, Rettangolo, Rombo, Quadrato]
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo]

【讨论】:

  • 好的,谢谢。我将非常感激,因为我尝试使用 remove 方法在 2 个列表上进行迭代,但运气不好。
  • 在 for each 循环中切换 a1 和 a2 以获得另一个结果。然后你可以将它们添加到你的输出语句中。
  • 在调用for (String s: a1) 之前,您可以先调用if Collections.disjoint(a1, a2) then print a1disjoint = 没有共同的元素,所以打印整个数组。 docs.oracle.com/javase/1.5.0/docs/api/java/util/…, java.util.Collection)
  • 我特别喜欢 a2.remove(s) 语句。我喜欢这样一个事实,即删除不存在的项目是无操作的。非常优雅。
【解决方案2】:

这两个类可能会有所帮助。让我知道如何进一步改进这一点。 随意在您自己的工作中使用下面的代码。 我必须指出,当前的代码没有处理重复的列表元素。

import java.util.List;

public class ListDiff<T> {

    private List<T> removed;
    private List<T> added;

    public ListDiff(List<T> removed, List<T> added) {
        super();
        this.removed = removed;
        this.added = added;
    }

    public ListDiff() {
        super();
    }

    public List<T> getRemoved() {
        return removed;
    }

    public List<T> getAdded() {
        return added;
    }

}

实用程序类。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ListUtil {

    public static <T> ListDiff<T> diff(List<T> one, List<T> two) {

        List<T> removed = new ArrayList<T>();
        List<T> added = new ArrayList<T>();

        for (int i = 0; i < one.size(); i++) {
            T elementOne = one.get(i);
            if (!two.contains(elementOne)) {
                //element in one is removed from two
                removed.add(elementOne);
            }
        }

        for (int i = 0; i < two.size(); i++) {
            T elementTwo = two.get(i);
            if (!one.contains(elementTwo)) {
                //element in two is added.
                added.add(elementTwo);
            }
        }

        return new ListDiff<T>(removed, added);
    }

    public static <T> ListDiff<T> diff(List<T> one, List<T> two, Comparator<T> comparator) {
        List<T> removed = new ArrayList<T>();
        List<T> added = new ArrayList<T>();

        for (int i = 0; i < one.size(); i++) {
            T elementOne = one.get(i);
            boolean found = false;

            //loop checks if element in one is found in two.
            for (int j = 0; j < two.size(); j++) {
                T elementTwo = two.get(j);
                if (comparator.compare(elementOne, elementTwo) == 0) {
                    found = true;
                    break;
                }
            }
            if (found == false) {
                //element is not found in list two. it is removed.
                removed.add(elementOne);
            }
        }

        for (int i = 0; i < two.size(); i++) {
            T elementTwo = two.get(i);
            boolean found = false;

            //loop checks if element in two is found in one.
            for (int j = 0; j < one.size(); j++) {
                T elementOne = one.get(j);
                if (comparator.compare(elementTwo, elementOne) == 0) {
                    found = true;
                    break;
                }
            }
            if (found == false) {
                //it means element has been added to list two. 
                added.add(elementTwo);
            }

        }

        return new ListDiff<T>(removed, added);
    }

    public static void main(String args[]) {
        String[] arr1 = { "london", "newyork", "delhi", "singapore", "tokyo", "amsterdam" };
        String[] arr2 = { "london", "newyork", "delhi", "singapore", "seoul", "bangalore", "oslo" };

        ListDiff<String> ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2));
        System.out.println(ld.getRemoved());
        System.out.println(ld.getAdded());

        ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2), new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        }); //sample for using custom comparator
        System.out.println(ld.getRemoved());
        System.out.println(ld.getAdded());
    }
}

【讨论】:

    【解决方案3】:

    这里有三个解决方案。

    使用 remove 方法的实现。

    public static boolean same(List<String> list1, List<String> list2){
        if (list1.size() != list2.size())
            return false;
        List<String> temp = new ArrayList<String>(list1);
        temp.removeAll(list2);
        return temp.size() == 0;
    }
    

    排序然后比较的解决方案。

    public static boolean same(List<String> list1, List<String> list2){
        if (list1.size() != list2.size())
            return false;
        Collections.sort(list1);
        Collections.sort(list2);
        for (int i=0;i<list1.size();i++){
            if (!list1.get(i).equals(list2.get(i)))
                return false;
        }
        return true;
    }
    

    而且,为了好玩,您可以通过计算两个数组之间的字数差异来做到这一点。它不会是最有效的,但它可以工作并且可能有用。

    public static boolean same(List<String> list1, List<String> list2){
        Map<String,Integer> counts = new HashMap<String,Integer>();
        for (String str : list1){
            Integer i = counts.get(str);
            if (i==null)
                counts.put(str, 1);
            else
                counts.put(str, i+1);
        }
        for (String str : list2){
            Integer i = counts.get(str);
            if (i==null)
                return false; /// found an element that's not in the other
            else
                counts.put(str, i-1);
        }
        for (Entry<String,Integer> entry : counts.entrySet()){
            if (entry.getValue() != 0)
                return false;
        }
        return true;
    }
    

    【讨论】:

      【解决方案4】:

      这将为您解释的这个特定情况找到两个数组之间的交集。

      String[] A1 = { "Rettangolo", "Quadrilatero", "Rombo", "Quadrato" };
      String[] A2 = { "Rettangolo", "Rettangolo", "Rombo", "Quadrato" };
      ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(A1));
      ArrayList<String> a2 = new ArrayList<String>(Arrays.asList(A2));
      a1.removeAll(a2);
      System.out.println("I have found " + a1);
      

      【讨论】:

        【解决方案5】:

        希望对你有帮助

            String[] A1 =  {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
            String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
        
            Set<String> set1 = new HashSet<String>();
            Set<String> set2 = new HashSet<String>();
        
            set1.addAll(Arrays.asList(A1));
            set2.addAll(Arrays.asList(A2));
        
            set1.removeAll(set2);
            System.out.println(set1);// ==> [Quadrilatero]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-02
          • 1970-01-01
          • 2016-01-28
          • 1970-01-01
          • 2019-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多