desislava_topuzakova

02. Sets of Elements

Sep 24th, 2021
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. package Test;
  2.  
  3. import java.util.*;
  4.  
  5. public class Test {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8. LinkedHashSet<Integer> firstSet = new LinkedHashSet<>();
  9. LinkedHashSet<Integer> secondSet = new LinkedHashSet<>();
  10.  
  11. String input = scanner.nextLine();//"4 3".SPLIT -> ["4", "3"]
  12. int countFirstSet = Integer.parseInt(input.split("\\s+")[0]);
  13. int countSecondSet = Integer.parseInt(input.split("\\s+")[1]);
  14.  
  15. //1. напълним двата сета
  16. for (int i = 0; i < countFirstSet; i++) {
  17. int number = Integer.parseInt(scanner.nextLine());
  18. firstSet.add(number);
  19. }
  20.  
  21. for (int i = 0; i < countSecondSet; i++) {
  22. int number = Integer.parseInt(scanner.nextLine());
  23. secondSet.add(number);
  24. }
  25. // 2. взимаме елементите, които ги има в двата сета
  26. //1. нов сет за съхранение на поввтарящите елементи
  27. //{1, 3, 5, 7}
  28. //{3, 4, 5}
  29. LinkedHashSet<Integer> duplicatedElements = new LinkedHashSet<>();
  30. for (int number : firstSet) {
  31. if (secondSet.contains(number)) {
  32. duplicatedElements.add(number);
  33. }
  34. }
  35.  
  36. //{1, 3, 5, 7}
  37. //{3, 4, 5}
  38. //firstSet.retainAll(secondSet);
  39. //в първия сет остават елементите, които ги има във втория
  40.  
  41. duplicatedElements.forEach(number -> System.out.print(number + " "));
  42.  
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment