settingsAccountsettings
Menusettings

Q: Sets of Elements - Java Task (Sets)

+14 votes

On the first line you are given the length of two sets n and m. On the next n + m lines there are n numbers that are in the first set and m numbers that are in the second one. Find all non-repeating element that appears in both of them, and print them at the console:

Set with length n = 4: {1, 3, 5, 7}

Set with length m = 3: {3, 4, 5}

Set that contains all repeating elements -> {3, 5}

Examples:

Input

Output

4 3

1

3

5

7

3

4

5

3 5

2 2

1

3

1

5

1

 
asked in Java category by user mitko
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

Here's my solution (read the comments in the code):

import java.util.HashSet;
import java.util.Scanner;

public class Pr_02_SetsOfElements {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int m = sc.nextInt();

        HashSet<Integer> set1 = new HashSet<>();
        HashSet<Integer> set2 = new HashSet<>();

        int input;

        for (int i = 0; i < n; i++) {//ADDING ELEMENTS TO set1
            input = sc.nextInt();
            set1.add(input);
        }

        for (int i = 0; i < m; i++) {//ADDING ELEMENTS TO set2
            input = sc.nextInt();
            set2.add(input);
        }

        set1.retainAll(set2);//ADDING + AFTERWARDS SHOWING ONLY THE COMMON ELEMENTS FROM BOTH: set + set2

        for (Integer integer : set1) {
            System.out.print(integer + " ");
        }
    }
}
answered by user eiorgert
edited by user golearnweb
...