用map性能高些
private <T> List<T> getNewList(List<T> allList, List<T> existList) {
Map<T, Integer> map = new HashMap<>(16);
for (int i = 0; i < allList.size(); i++) {
map.put(allList.get(i), i);
}
for (int i = 0; i < existList.size(); i++) {
Integer pos = map.get(existList.get(i));
if (pos == null) {
continue;
}
allList.set(pos, null);
}
for (int i = allList.size() - 1; i >= 0; i--) {
if (allList.get(i) == null) {
allList.remove(i);
}
}
return allList;
}
这段代码展示了一个使用Map来提高处理两个列表交集性能的方法。首先,将第一个列表的所有元素及其索引存入Map中,然后遍历第二个列表,通过Map查找元素在第一个列表中的位置并置空,最后删除所有空值,实现高效地移除第二个列表中的元素。
1508

被折叠的 条评论
为什么被折叠?



