【问题标题】:fast way to update elements of a list comparing with another list与另一个列表比较更新列表元素的快速方法
【发布时间】:2014-04-28 23:50:37
【问题描述】:
我有两个具有整数 ID 的列表,一个旧列表和一个新列表。
现在我想做三个步骤:
1. 检查(旧)List1 中的哪些 ID 在(新)List2 中也找到
2.从List1中删除步骤1之后List2中没有的所有元素
3. 将列表 2 中所有缺失的 ID 添加到列表 1
我正在考虑添加两个布尔数组并在找到一个元素时设置一个标志,稍后我可以从 List1 中删除 IDs 元素并在 List1 中添加 List2 中未检查的 ID。
也许有更好的方法?
【问题讨论】:
标签:
java
arrays
list
loops
iteration
【解决方案1】:
试试这个方法:
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 5, 6));
list1.retainAll(list2);
list2.removeAll(list1);
list1.addAll(list2);
System.out.println(list1);
输出:
[2, 3, 5, 6]
【解决方案2】:
将所有内容放在查找表中,例如使用 HashSet。