int数组交并差集

public int[] operate(int[] a, int[] b, String operation){
		
		Set<Integer> aSet = new TreeSet<>(Arrays.stream(a).boxed().collect(Collectors.toList()));
		Set<Integer> bSet = new TreeSet<>(Arrays.stream(b).boxed().collect(Collectors.toList()));
		Set<Integer> resultSet = new TreeSet<>();
		switch (operation) {
			case "UNION":			//并集
				aSet.addAll(bSet);
				resultSet = aSet;
				break;
			case "INTERSECTION":	//交集
				resultSet.addAll(aSet);
				resultSet.retainAll(bSet);
				break;
			case "SYMMETRIC DIFFERENCE":	//差集
				resultSet.addAll(aSet);
				resultSet.removeAll(bSet);
				Set<Integer> removeSet = new TreeSet<>();
				removeSet.addAll(bSet);
				removeSet.removeAll(aSet);
				resultSet.addAll(removeSet);
				break;
	
			default:
				break;
		}
		int[] resultInt = new int[resultSet.size()];
		Iterator<Integer> it = resultSet.iterator();
		int i = 0;
		while (it.hasNext()) {
			resultInt[i] = it.next();
			i++;
		}
		return resultInt;
	}

 

posted @ 2017-06-08 00:24  Yannis-chen  阅读(146)  评论(0编辑  收藏  举报