Set Operations

Lab Java Intermediate 20 points

Read two lines of integers A and B. Using TreeSets and addAll/retainAll/removeAll, print the union, intersection and A − B.

Input

Two lines of integers.

Output

Three lines, each a set like [1, 2].

Example

Input

1 2 3 4
3 4 5

Output

[1, 2, 3, 4, 5]
[3, 4]
[1, 2]
Sample input available Sample output available
Editor
Java

Hints

Copy A first so the original isn't changed: new TreeSet<>(a).

Solution explanation

The bulk methods modify the set they're called on, so work on copies.

Show solution
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    static Set<Integer> readSet(Scanner sc) {
        Set<Integer> set = new TreeSet<Integer>();
        for (String t : sc.nextLine().trim().split("\\s+")) {
            set.add(Integer.parseInt(t));
        }
        return set;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Set<Integer> a = readSet(sc);
        Set<Integer> b = readSet(sc);
        Set<Integer> union = new TreeSet<Integer>(a);
        union.addAll(b);
        Set<Integer> inter = new TreeSet<Integer>(a);
        inter.retainAll(b);
        Set<Integer> diff = new TreeSet<Integer>(a);
        diff.removeAll(b);
        System.out.println(union);
        System.out.println(inter);
        System.out.println(diff);
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD