比较 2 个 ArrayLists 的简单方法 [英] Simple way to compare 2 ArrayLists

查看:21
本文介绍了比较 2 个 ArrayLists 的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 arraylists of string object.

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

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

I have some logic where i need to process the source list and will end up with the destination list. The destination list will have some additional elements added to the source list or removed from source list.

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

My expected output is 2 ArrayList of string where the first list should have all the strings removed from the source and second list should have all the strings newly added to the source.

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

Any simpler method to achieve this?

推荐答案

Convert Lists to Collection 并使用 removeAll

Convert Lists to Collection and use 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]

这篇关于比较 2 个 ArrayLists 的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆