【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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM