SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

Write a method called symmetricSetDifference that accepts two Sets as parameters and returns a new Set containing their symmetric set difference (that is, the set of elements contained in either of the two sets but not in both). For example, the symmetric difference between the sets {1, 4, 7, 9} and {2, 4, 5, 6, 7} is {1, 2,5, 6, 9}.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package collections;

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

public class SetDiffrence {

	public static Set<String> symmetricSetDiffrence(Set<String> set1, Set<String> set2) {
        
        // Set doesn't allow duplicates thus adding both gives us the symmetric set diffrence.
		set1.addAll(set2);
		set1 = (HashSet<String>) set1;
		return set1;
	}

	public static void main(String args[]) {
		Set<String> set1 = new HashSet<String>();
		Set<String> set2 = new HashSet<String>();
		Collections.addAll(set1, "a", "b", "c", "d");
		Collections.addAll(set2, "b", "k", "d", "a");

		System.out.print("the symmetric set diffrence is: [ ");
		Set<String> unique = SetDiffrence.symmetricSetDiffrence(set1, set2);
		for (String s : unique)
			System.out.print(s+"  ");
		System.out.print("]");
		
	}

}
Output:

the symmetric set diffrence is: [ a  b  c  d  k  ]

 

0 0

Discussions

Post the discussion to improve the above solution.