两个List集合如何去重,取交集,并集,差集

List a = new ArrayList<>(32);

a.add(1);

a.add(2);

a.add(3);

List b = new ArrayList<>(32);

b.add(2);

b.add(3);

b.add(3);

1.并集

a.addAll(b);

运行结果:1,2,3,2,3,3

2.无重复并集
a.removeAll(b);
a.addAll(b);

运行结果:1,2,3,3

3.交集

a.retainAll(b);

运行结果: 2,3

4.差集
a.removeAll(b);

运行结果:1

5,去重复(JDK8特性)

List newList = b.stream().distinct().collect(Collectors.toList());

运行结果:2,3

猜你喜欢

转载自blog.csdn.net/Liuyooer/article/details/84842644