关于集合运算

来源:互联网 发布:电力cad软件 编辑:程序博客网 时间:2024/06/05 20:53

昨天被问到一个问题,就是给定两个集合Set1和Set2,求出在Set1中但是不在Set2中和在Set2中但是不在Set1中的元素集合,看了一眼,题意如下:



题目需要求得就是除去重叠部分的元素,代码如下:

import java.util.HashSet;import java.util.Set;public class Main {public static void main(String[] args) {Set<Integer> s1=new HashSet<Integer>();Set<Integer> s2=new HashSet<Integer>();for(int i=0;i<=5;i++){s1.add(i); // 0, 1, 2, 3, 4, 5}for(int i=4;i<=7;i++){s2.add(i); //4, 5, 6, 7}Set<Integer> s3=solve(s1,s2);for(Integer e:s3){System.out.println(e); //0, 1, 2, 3, 6, 7}}//做集合运算,返回      (s1 ∪ s2) - ( s1 ∩ s2 )public static <T> Set<T> solve(Set<T> s1,Set<T> s2){Set<T> res=new HashSet<T>();for(T t:s1) if(!s2.contains(t)) res.add(t);for(T t:s2) if(!s1.contains(t)) res.add(t);return res;}}


0 0