开发中比较两个集合的不同点,例如需要对于两个集合取差集,下面列举了几种方式。
方式1:使用java 8的stream流
整个集合过滤
list<string> list1 = arrays.aslist("a", "b", "c", "d");
list<string> list2 = arrays.aslist("c", "d", "e", "f");
// 获取差集
list<string> difference1 = list1.stream()
.filter(element -> !list2.contains(element))
.collect(collectors.tolist());
// 获取list2中不在list1的元素
list<string> difference2 = list2.stream()
.filter(element -> !list1.contains(element))
.collect(collectors.tolist());
根据集合中对象的属性来过滤
// 根据集合中对象的name属性来过滤
public void teststreamnonematch(list<studentdto> originaldto, list<studentdto> newdto) {
list<studentdto> boy = originaldto.stream()
.filter(item -> item.getgender() == 1
&& newdto.stream().anymatch(dto -> dto.getname().equals(item.getname()))).collect(collectors.tolist());
log.info("性别为男生,且名字相同的人员为{}", jsonobject.tojsonstring(boy));
}
方式2:使用java集合类的removeall()方法
list<string> list1copy = new arraylist<>(list1);
list<string> list2copy = new arraylist<>(list2);
// 获取list1中不在list2的元素
list1copy.removeall(list2);
list<string> difference1 = list1copy;
// 获取list2中不在list1的元素
list2copy.removeall(list1);
list<string> difference2 = list2copy;
方式3:使用google guava库的sets.difference()方法
list<string> list1 = ...;
list<string> list2 = ...;
// 获取list1中不在list2的元素
set<string> set1 = sets.newhashset(list1);
set<string> set2 = sets.newhashset(list2);
set<string> difference1 = sets.difference(set1, set2);
// 获取list2中不在list1的元素
set<string> difference2 = sets.difference(set2, set1);
方式4:使用apache commons collections的listutils.subtract()方法
list<string> list1 = ...;
list<string> list2 = ...;
// 获取list1中不在list2的元素
list<string> difference1 = listutils.subtract(list1, list2);
// 获取list2中不在list1的元素
list<string> difference2 = listutils.subtract(list2, list1);
注意:方式有很多,大家可根据项目需求和已引入的库,选择合适的方法来计算集合的差集。
有更好的方式或想法,欢迎大家评论区留言,互相学习~
发表评论