Advertisement
Ligh7_of_H3av3n

02. Sets of Elements

May 21st, 2024
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. package Uprajnenie;
  2.  
  3. import java.util.LinkedHashSet;
  4. import java.util.Scanner;
  5. import java.util.Set;
  6.  
  7. public class SetsOfElements {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.  
  12.         // Read lengths of the two sets
  13.         int n = scanner.nextInt();
  14.         int m = scanner.nextInt();
  15.         scanner.nextLine(); // Consume the newline character
  16.  
  17.         Set<Integer> set1 = new LinkedHashSet<>();
  18.         Set<Integer> set2 = new LinkedHashSet<>();
  19.  
  20.         // Read N numbers for the first set
  21.         for (int i = 0; i < n; i++) {
  22.             int num = scanner.nextInt();
  23.             set1.add(num);
  24.         }
  25.  
  26.         // Read M numbers for the second set
  27.         for (int i = 0; i < m; i++) {
  28.             int num = scanner.nextInt();
  29.             set2.add(num);
  30.         }
  31.  
  32.         // Find the intersection of the two sets
  33.         set1.retainAll(set2);
  34.  
  35.         // Print the common elements
  36.         for (int num : set1) {
  37.             System.out.print(num + " ");
  38.         }
  39.  
  40.         scanner.close();
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement