创建两个散列规则集,{“George”,"Jim","John","Blake","Kevin","Michael"} {"George","Katie","Kevin","Michael","Ryan"}求他们的并集,差集,交集。
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class execise22_1 {
public static void main(String args[]) {
Set<String> setFirst = new HashSet<String>();
Set<String> setSecond = new HashSet<String>();
setFirst.add("George");
setFirst.add("Jim");
setFirst.add("John");
setFirst.add("Blake");
setFirst.add("Kevin");
setFirst.add("Michael");
setSecond.add("George");
setSecond.add("Katie");
setSecond.add("Kevin");
setSecond.add("Michael");
setSecond.add("Ryan");
Set<String> union = new execise22_1().getUnion(setFirst, setSecond);
Set<String> difference = new execise22_1().getDifference(setFirst,setSecond);
Set<String> common = new execise22_1().getCommon(setFirst, setSecond);
System.out.println(difference);
System.out.println(union);
System.out.println(common);
}
/**
* 求差集
*
* @param setFirst
* @param setSecond
* @return
*/
private Set<String> getDifference(Set<String> setFirst,
Set<String> setSecond) {
Set<String> setDifference = new HashSet<String>();
Iterator<String> iteratorFirst = setFirst.iterator();
while (iteratorFirst.hasNext()) {
String temp = iteratorFirst.next();
if (!setSecond.contains(temp)) {
setDifference.add(temp);
}
}
Iterator<String> iteratorSecond = setSecond.iterator();
while (iteratorSecond.hasNext()) {
String temp = iteratorSecond.next();
if (!setFirst.contains(temp)) {
setDifference.add(temp);
}
}
return setDifference;
}
/**
* 求并集合
*
* @param setFirst
* @param setSecond
* @return
*/
private Set<String> getUnion(Set<String> setFirst, Set<String> setSecond) {
Set<String> unionSet = new HashSet<String>(setFirst);
unionSet.addAll(setSecond);
return unionSet;
}
/**
* 求交集
* @param setFirst
* @param setSecond
* @return
*/
private Set<String> getCommon(Set<String> setFirst, Set<String> setSecond) {
Set<String> commonSet = new HashSet<String>();
Iterator<String> iteratorFirst = setFirst.iterator();
while (iteratorFirst.hasNext()) {
String temp = iteratorFirst.next();
if (setSecond.contains(temp)) {
commonSet.add(temp);
}
}
return commonSet;
}
}
输出:
[Katie, Jim, Blake, Ryan, John]
[Katie, Jim, Blake, Ryan, John, Kevin, George, Michael]
[Kevin, George, Michael]