這篇文章分享Set 的4個用法:
- 交集
- 相減集合
- 聯集
- 遍歷
交集
兩個集合中同時都存在的元素
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.addAll(setA);
resSet.removeAll(setB);
return resSet;
取聯集
兩個集合中全部的元素
HashSet setA = new HashSet<>();
HashSet setB = new HashSet<>();
HashSet resSet = new HashSet<>();
resSet.addAll(setA);
resSet.addAll(setB);
return resSet;
存在於子集合
Set<Integer> setA = new HashSet<>();
setA.add(1);
setA.add(2);
Set<Integer> setB = new HashSet<>();
setB.add(2);
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());