020-002-012

Set Operations (Union, Intersection, Difference)

Hard

Problem Description

Set Operations (Union, Intersection, Difference)

In this problem: You will create a SetOperations class that implements union, intersection, and difference set operations on two collections (HashSets).

Learning Objective: Understand how to implement set operations (addAll, retainAll, removeAll) using Set

Overview

Mathematical set operations can be implemented using Java Sets. addAll computes the union, retainAll computes the intersection, and removeAll computes the difference. Create copies before operations to avoid modifying the original sets.

Specifications

  • Implement 3 static methods in SetOperations class
  • union(Set, Set): returns the union
  • intersection(Set, Set): returns the intersection
  • difference(Set, Set): returns the difference (first argument minus second)
  • Convert results to TreeSet for sorted output

Output Format

Set A: [1, 2, 3, 4, 5]
Set B: [3, 4, 5, 6, 7]
Union: [1, 2, 3, 4, 5, 6, 7]
Intersection: [3, 4, 5]
Difference (A-B): [1, 2]

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up