首页 > 代码库 > java 集合交并补

java 集合交并补

通过使用泛型方法和Set来表达数学中的表达式:集合的交并补,在以下三个方法中都将第一个参数Set复制了一份,并未直接修改参数中Set。
package Set;

import java.util.HashSet;
import java.util.Set;

public class Sets {
	public  static <T> Set<T> intersection(Set<T> s1, Set<T> s2) {
		Set<T> result = new HashSet<T>(s1);
		result.retainAll(s2);
		return result;
	}

	public  static <T> Set<T> union(Set<T> s1, Set<T> s2) {
		Set<T> result = new HashSet<T>(s1);
		result.addAll(s2);
		return result;
	}
	
	//Subtract subset from superset
	public  static <T> Set<T> difference (Set<T> superset, Set<T> subset) {
		Set<T> result = new HashSet<T>(superset);
		result.addAll(subset);
		return result;
	}
	
	//Reflexive --everything not in their intersection
	public static <T> Set<T> complement(Set<T>s1,Set<T> s2){
		return difference(union(s1,s2),intersection(s1,s2));
	}
}

java 集合交并补