【问题标题】:Simple way to compare 2 ArrayLists比较 2 个 ArrayLists 的简单方法
【发布时间】:2013-10-09 22:05:51
【问题描述】:

我有 2 个字符串对象的数组列表。

List<String> sourceList = new ArrayList<String>();
List<String> destinationList = new ArrayList<String>();

我有一些逻辑需要处理源列表并最终得到目标列表。目标列表将添加一些附加元素到源列表或从源列表中删除。

我的预期输出是 2 个字符串的 ArrayList,其中第一个列表应从源中删除所有字符串,第二个列表应将所有字符串新添加到源中。

有没有更简单的方法来实现这一点?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 对不起老兄,读了 3 遍。没有得到你要问的。顺便说一句,你的代码在哪里?
  • 用for循环来实现。正在寻找一些第三方 api..

标签: java list arraylist


【解决方案1】:

将列表转换为Collection 并使用removeAll

    Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
    Collection<String> listTwo = new ArrayList(Arrays.asList("a","b",  "d", "e", "f", "gg", "h"));


    List<String> sourceList = new ArrayList<String>(listOne);
    List<String> destinationList = new ArrayList<String>(listTwo);


    sourceList.removeAll( listTwo );
    destinationList.removeAll( listOne );



    System.out.println( sourceList );
    System.out.println( destinationList );

输出:

[c, g]
[gg, h]

[编辑]

其他方式(更清楚)

  Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));

    List<String> sourceList = new ArrayList<String>(list);
    List<String> destinationList = new ArrayList<String>(list);

    list.add("boo");
    list.remove("b");

    sourceList.removeAll( list );
    list.removeAll( destinationList );


    System.out.println( sourceList );
    System.out.println( list );

输出:

[b]
[boo]

【讨论】:

  • 如果要通过“removeAll”比较自定义对象,不要忘记实现“equals”和“hashCode”方法。
【解决方案2】:

这应该检查两个列表是否相等,它首先进行一些基本检查(即空值和长度),然后排序并使用 collections.equals 方法检查它们是否相等。

public  boolean equalLists(List<String> a, List<String> b){     
    // Check for sizes and nulls

    if (a == null && b == null) return true;


    if ((a == null && b!= null) || (a != null && b== null) || (a.size() != b.size()))
    {
        return false;
    }

    // Sort and compare the two lists          
    Collections.sort(a);
    Collections.sort(b);      
    return a.equals(b);
}

【讨论】:

  • 您在检查列表大小后检查列表是否为空......这是错误的
  • (a == null &amp;&amp; b!= null) || (a != null &amp;&amp; b== null))这部分,你可以检查(a != b)
【解决方案3】:

List 转换为String 并检查字符串是否相同

import java.util.ArrayList;
import java.util.List;



/**
 * @author Rakesh KR
 *
 */
public class ListCompare {

    public static boolean compareList(List ls1,List ls2){
        return ls1.toString().contentEquals(ls2.toString())?true:false;
    }
    public static void main(String[] args) {

        ArrayList<String> one  = new ArrayList<String>();
        ArrayList<String> two  = new ArrayList<String>();

        one.add("one");
        one.add("two");
        one.add("six");

        two.add("one");
        two.add("two");
        two.add("six");

        System.out.println("Output1 :: "+compareList(one,two));

        two.add("ten");

        System.out.println("Output2 :: "+compareList(one,two));
    }
}

【讨论】:

  • 但你不知道顺序!
【解决方案4】:

如果您的要求是保持插入顺序并检查两个数组列表的内容,那么您应该执行以下操作:

List<String> listOne = new ArrayList<String>();
List<String> listTwo = new ArrayList<String>();

listOne.add("stack");
listOne.add("overflow");

listTwo.add("stack");
listTwo.add("overflow");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

这将返回 true。

但是,如果您更改顺序,例如:

listOne.add("stack");
listOne.add("overflow");

listTwo.add("overflow");
listTwo.add("stack");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

由于排序不同,将返回 false。

【讨论】:

    【解决方案5】:

    答案在@dku-rajkumar帖子中给出。

    ArrayList commonList = CollectionUtils.retainAll(list1,list2);

    【讨论】:

      【解决方案6】:

      最简单的方法是逐个遍历源列表和目标列表 像这样:

      List<String> newAddedElementsList = new ArrayList<String>();
      List<String> removedElementsList = new ArrayList<String>();
      for(String ele : sourceList){
          if(destinationList.contains(ele)){
              continue;
          }else{
              removedElementsList.add(ele);
          }
      }
      for(String ele : destinationList){
          if(sourceList.contains(ele)){
              continue;
          }else{
              newAddedElementsList.add(ele);
          }
      }
      

      虽然如果你的源列表和目标列表有很多元素,它可能效率不高,但肯定更简单。

      【讨论】:

        【解决方案7】:
        boolean isEquals(List<String> firstList, List<String> secondList){
            ArrayList<String> commons = new ArrayList<>();
        
            for (String s2 : secondList) {
                for (String s1 : firstList) {
                   if(s2.contains(s1)){
                       commons.add(s2);
                   }
                }
            }
        
            firstList.removeAll(commons);
            secondList.removeAll(commons);
            return !(firstList.size() > 0 || secondList.size() > 0) ;
        }
        

        【讨论】:

          【解决方案8】:

          据我正确理解,我认为使用 4 个列表最容易: - 您的来源列表 - 您的目的地列表 - 一个已移除的ItemsList - 一个newAddedItemsList

          【讨论】:

            【解决方案9】:
            private int compareLists(List<String> list1, List<String> list2){
                Collections.sort(list1);
                Collections.sort(list2);
            
                int maxIteration = 0;
                if(list1.size() == list2.size() || list1.size() < list2.size()){
                    maxIteration = list1.size();
                } else {
                    maxIteration = list2.size();
                }
            
                for (int index = 0; index < maxIteration; index++) {
                    int result = list1.get(index).compareTo(list2.get(index));
                    if (result == 0) {
                        continue;
                    } else {
                        return result;
                    }
                }
                return list1.size() - list2.size();
            }
            

            【讨论】:

              【解决方案10】:
              List<String> oldList = Arrays.asList("a", "b", "c", "d", "e", "f");
              List<String> modifiedList = Arrays.asList("a", "b", "c", "d", "e", "g");
              
              List<String> added = new HashSet<>(modifiedList);
              List<String> removed = new HashSet<>(oldList);
              
              modifiedList.stream().filter(removed::remove).forEach(added::remove);
              
              // added items
              System.out.println(added);
              // removed items
              System.out.println(removed);
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2013-12-05
                • 1970-01-01
                • 1970-01-01
                • 2018-07-21
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-02-15
                相关资源
                最近更新 更多