# Java Set 交集/相減集合/聯集/遍歷

Posted in :

• 交集
• 相減集合
• 聯集
• 遍歷

## 交集

``HashSet setA = new HashSet<>();HashSet setB = new HashSet<>();HashSet resSet = new HashSet<>();resSet.addAll(setA);resSet.retainAll(setB);return resSet;``

## 相減集合

``````HashSet<String> setA = new HashSet<>();
HashSet<String> setB = new HashSet<>();
HashSet<String> resSet = new HashSet<>();
resSet.removeAll(setB);
return resSet;``````

## 取聯集

``````HashSet setA = new HashSet<>();
HashSet setB = new HashSet<>();
HashSet resSet = new HashSet<>();
return resSet;``````

## 存在於子集合

``````Set<Integer> setA = new HashSet<>();

Set<Integer> setB = new HashSet<>();

boolean result = setA.containsAll(setB );
System.out.println("subset of Numbers? " + result);``````

## Traverse through a HashSet

Using for-each loop

``````for (String i : h)
System.out.println(i);   ``````

Using forEach method

``h.forEach(i -> System.out.println(i));``

Using Iterators

``````Iterator<String> i = you_set.iterator();
while (i.hasNext())
System.out.println(i.next());``````