【Java】对两个Set取交集,差集,并集

2021/9/29 22:12:57

本文主要是介绍【Java】对两个Set取交集,差集,并集,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、取交集(取两个集合中都存在的元素)

HashSet<String> setA = new HashSet<>();
HashSet<String> setB = new HashSet<>();
//用于存放结果
HashSet<String> resSet = new HashSet<>();
resSet.addAll(setA);
resSet.retainAll(setB);
return resSet;

2、取差集(取存在一个集合中,但不存在于另外一个集合中的元素)

HashSet<String> setA = new HashSet<>();
HashSet<String> setB = new HashSet<>();
//用于存放结果
HashSet<String> resSet = new HashSet<>();
resSet.addAll(setA);
resSet.removeAll(setB);
return resSet;

3、取交集(取两个集合中全部的元素,这个很简单,都把他们添加进去就行)

HashSet<String> setA = new HashSet<>();
HashSet<String> setB = new HashSet<>();
//用于存放结果
HashSet<String> resSet = new HashSet<>();
resSet.addAll(setA);
resSet.addAll(setB);
return resSet;


这篇关于【Java】对两个Set取交集,差集,并集的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程