集合间找差异、找相同、合并集合的问题
1. 基本类型
// 找相交
final List<String> aList = Lists.newArrayList("a", "b", "c", "d", "e", "dwew");
final List<String> bList = Lists.newArrayList("a", "b", "c", "de", "ewefqq", "dwew");
final List<String> collect = aList.stream().filter (o -> bList.contains(o)).collect(Collectors.toCollection(ArrayList::new));
System.out.println("collect = " + collect); // [a, b, c, dwew]
// 找aList独有的
final List<String> aList = Lists.newArrayList("a", "b", "c", "d", "e", "dwew");
final List<String> bList = Lists.newArrayList("a", "b", "c", "de", "ewefqq", "dwew");
final List<String> collect1 = aList.stream().filter(o -> !bList.contains(o)).collect(Collectors.toCollection(ArrayList::new));
System.out.println("collect1 = " + collect1);
// 合并两个list,并去重
final List<String> aList = Lists.newArrayList("a", "b", "c", "d", "e", "dwew");
final List<String> bList = Lists.newArrayList("a", "b", "c", "de", "ewefqq", "dwew");
final List<String> collect2 = Stream.concat(aList.stream(), bList.stream()).distinct().collect(Collectors.toCollection(ArrayList::new));
System.out.println("collect2 = " + collect2);
2、实体类
// 找出aList 独有的集合
public static void main(String[] args) throws ExecutionException {
final List<Answer> aList = Lists.newArrayList(Answer.build(1, "dsaf"), Answer.build(2, "dsafd"), Answer.build(3, "dsdsdaf"));
final List<Answer> bList = Lists.newArrayList(Answer.build(2, "dsafd"), Answer.build(3, "dffsaddfd"), Answer.build(4, "dsdssdaf"));
final List<Answer> collect = aList.stream().filter(o -> !checkBListHas(o, bList)).collect(Collectors.toCollection(ArrayList::new));
System.out.println("collect = " + collect);
}
// 检查 one 在bList 中是否存在,存在则返加true
private static boolean checkBListHas(Answer one, List<Answer> bList) {
for (Answer answer : bList) {
if (answer.getId() == one.getId() && answer.getSubjectId().equals(one.getSubjectId())) { // todo 这里需要完善健壮性,增加判空
return true;
}
}
return false;
}
// 合并两个list 并去重
final List<Answer> aList = Lists.newArrayList(Answer.build(1, "dsaf"), Answer.build(2, "dsafd"), Answer.build(3, "dsdsdaf"));
final List<Answer> bList = Lists.newArrayList(Answer.build(2, "dsafd"), Answer.build(3, "dffsaddfd"), Answer.build(4, "dsdssdaf"));
final List<Answer> collect = Stream.concat(aList.stream(), bList.stream()).collect(Collectors.toCollection(ArrayList::new));
final TreeSet<Answer> answers = new TreeSet<>(new Comparator<Answer>() {
@Override
public int compare(Answer o1, Answer o2) {
if ((o1.getId() == o2.getId()) && checkString(o1.getSubjectNo(), o2.getSubjectNo())) {
return 0; // 返回0代表相同
} else {
return 1; // 返回1 代表不同
}
}
private boolean checkString(Integer subjectNo, Integer subjectNo1) {
if(subjectNo==subjectNo1) return true;
if (subjectNo != null && subjectNo1 != null && subjectNo.equals(subjectNo1)) {
return true;
}
return false;
}
});
final boolean b = answers.addAll(collect);
final List<Answer> answers1 = new ArrayList<>(answers);
System.out.println("answers1 = " + answers1);

浙公网安备 33010602011771号