Java中的列表差异 [英] List difference in java

查看:65
本文介绍了Java中的列表差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个ArrayList<Integer>如下:

原始:12, 16, 17, 19, 101

已选择:16, 19, 107, 108, 109

我想对这些列表进行区别,以使最终我有两个列表:

I want to do difference on these lists such that in the end I have two lists:

添加:108,109,107

删除:12, 17, 101

原始列表和所选列表的长度各不相同,一个列表可以比另一个列表大/小

Length of original and selected lists varies and one can be greater/smaller than the other

推荐答案

List<Integer> original = Arrays.asList(12,16,17,19,101);
List<Integer> selected = Arrays.asList(16,19,107,108,109);

ArrayList<Integer> add = new ArrayList<Integer>(selected);
add.removeAll(original);
System.out.println("Add: " + add);

ArrayList<Integer> remove = new ArrayList<Integer>(original);
remove.removeAll(selected);
System.out.println("Remove: " + remove);

输出:

Add: [107, 108, 109]
Remove: [12, 17, 101]

使用Collection的removeAll方法. 请参阅javadocs

Uses Collection's removeAll method. See javadocs.

这篇关于Java中的列表差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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