【问题标题】:Compare two different arraylists and get differences java [duplicate]比较两个不同的数组列表并获得差异java [重复]
【发布时间】:2014-05-12 17:25:32
【问题描述】:

我有两个数组列表,我正在寻找一种有效的方法来计算不同值的数量。

一些示例列表:

List<String> list = new ArrayList<String>();
    list.add("String A");
    list.add("String B");
    list.add("String C");

List<String> anotherlist = new ArrayList<String>();
    list.add("String B");
    list.add("String A");
    list.add("String D");

您可以检查每个项目(因为顺序无关紧要)是否相同(纯概念):

    for(int i=0;i<list.size();i++)
    {
             for(int j=0;j<anotherlist.size();j++)
             {
                   if (item.get(i) == item.get(j)){
                       intDifferent = intDifferent+1;
                   } else {
                       intSame = intSame+1;
                   }
                   intTotal = intTotal+1
             }
    }

    //Some calculations with intdifferent en inttotal to find out how many different 
    //values we actually have  between the lists, in the case of the example, it 
    //should output 1

有没有更有效的方法来做到这一点?或者是否有关于如何完成此操作的示例或帖子?

【问题讨论】:

    标签: java android arraylist compare


    【解决方案1】:

    您应该考虑为此使用Sets。

    将一个数组中的所有项目放到HashSet 中,然后遍历另一个数组,检查它是否包含在Set 中。

    这将比每次循环 ArrayList 快​​得多。

    【讨论】:

    • 请告诉他也通过equals比较字符串。
    • @Seelenvirtuose 你当然是对的,但根据我的建议,他自己根本不做任何比较:)
    • 我知道。哈希数据结构处于最佳状态。 :-)
    【解决方案2】:

    以下算法最坏情况复杂度为O(n* log(n))

        // worst case O(nLog(n))
        Collections.sort(l1);
        // worst case O(nLog(n))
        Collections.sort(l2);
    
        // pointer for l1 list
        int p = 0;
    
        // pointer for l2 list
        int q = 0;
    
        int diffCounter = 0;
        // worst case N
        while (true) {
    
            if (p == l1.size() -1 ) {
                // remainig items in l2 list are diff
                diffCounter += (l2.size() -1) - q;
                break;
            }
            if (q == l2.size() -1 ) {
                diffCounter += (l1.size() - 1) - p;
            }
    
            int compareResult = l1.get(p).compareTo(l2.get(q));
            if (compareResult > 0) {
                p++;
                diffCounter++;
            } else if (compareResult < 0 ) {
                q++;
                diffCounter++;
            }
    

    `

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      相关资源
      最近更新 更多