020-003-002
Set Operations: Managing Collections Without Duplicates
Medium
Problem Description
HashSet Set Operations
In this problem, you will create a program that converts two integer lists into HashSets, finds their intersection (common elements) using the retainAll() method, sorts the result in ascending order, and displays it to standard output.
Use HashSet's retainAll() method to find the intersection.
Finding Intersection
Set<Integer> set1 = new HashSet<>(list1); Set<Integer> set2 = new HashSet<>(list2); set1.retainAll(set2); // set1 becomes the intersection
Learning Points
- retainAll() is a destructive operation that modifies the original set
- Convert to List and use Collections.sort() for sorted output
- Use addAll() for union, removeAll() for difference
Test Cases
※ Output examples follow programming industry standards
Normal case
Input:
4 1 2 3 4 4 3 4 5 6
Expected Output:
3 4
Boundary case
Input:
3 1 2 3 3 4 5 6
Expected Output:
No common elements
Your Solution
Current Mode:● My Code
99
1
2
3
4
5
6
7
8
9
10
›
⌄
⌄
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Write your code here
sc.close();
}
}
0 B / 5 MB
You have 10 free executions remaining
