java 两个List集合比较后获取多余、遗漏的最高效的几种方法
取多余
// 集合sourcelist中不存在而集合targetlist存在字符串
public static ArrayList<String> CompareList(ArrayList<String> sourcelist,ArrayList<String> targetlist) throws Exception {
//long starttime = System.currentTimeMillis();
String v_errorinfo = "";
ArrayList<String> al = null;
try {
//方法一 使用迭代器循环判断
// LinkedList ll = new LinkedList(targetlist);
// HashSet hs = new HashSet(sourcelist);
// Iterator iter = ll.iterator();// 采用Iterator迭代器进行数据的操作
// while (iter.hasNext()) {
// //如果源项包含目标项,则在ll中将对应的目标项删除,剩下的都是目标项比源项多的
// if (hs.contains(iter.next())) {
// iter.remove();
// }
// }
// al = new ArrayList(ll);
//方法二 直接调用removeAll,一次性将目标端list中包含源端list的项清除掉,剩下的就是多余的项
//通过将大集合转换为LinkedList,小集合转换为HashSet,并利用Iterator迭代器进行删除操作,可以显著提升效率
// 缺陷是无法判断哪个大哪个小
// LinkedList ll = new LinkedList(targetlist);
// HashSet hs = new HashSet(sourcelist);
// ll.removeAll(hs);
// al = new ArrayList(ll);
//方法三 使用hashset你可以使用filter和collect方法来找出多余的或遗漏的元素
Set<String> hssource = new HashSet(sourcelist);
Set<String> hstarget = new HashSet(targetlist);
// 找出hstarget独有的元素,也就是多余
Set<String> onlyInTarget = hstarget.stream()
.filter(id -> !hssource.contains(id))
.collect(Collectors.toSet());
al = new ArrayList(onlyInTarget);
} catch (Exception e) {
v_errorinfo = v_errorinfo + e.toString();
}
//有异常则抛出,中断执行
if (!(Objects.isNull(v_errorinfo)|| v_errorinfo.equalsIgnoreCase(""))) {
throw new Exception(v_errorinfo);
}
//long endtime = System.currentTimeMillis();
//System.out.println("取多余耗时:"+(endtime-starttime)+"ms");
return al;
}
取遗漏
// 集合sourcelist中存在而集合targetlist不存在字符串,将上述中函数中参数对调即可:
ArrayList<String> Result=CompareList(targetlist,sourcelist)
更多推荐


所有评论(0)