简单比较2的ArrayList的方式 [英] Simple way to compare 2 ArrayLists

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

问题描述

我有2个的ArrayList字符串的对象。

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串,其中第一列表应当具有从源和第二列表除去所有字符串应具有所有新添加到源。琴弦

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?

推荐答案

转换列表来收藏,并使用的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的ArrayList的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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