其他分享
首页 > 其他分享> > 集合间找差异、找相同、合并集合的问题

集合间找差异、找相同、合并集合的问题

作者:互联网

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 并去重

 

标签:合并,差异,List,aList,collect,bList,集合,final,Answer
来源: https://www.cnblogs.com/txt1024/p/15828121.html