比较 2 个数组列表的简单方法

2022-09-01 04:09:21

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

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

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

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

有什么更简单的方法来实现这一点吗?


答案 1

将列表转换为并使用CollectionremoveAll

    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]

答案 2

这应该检查两个列表是否相等,它首先执行一些基本检查(即 null 和 length),然后排序并使用 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);
}