关于集合运算

昨天被问到一个问题,就是给定两个集合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;
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值