Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. # Java Data Types Structures and Operations
  2.  
  3. ## Let see what we can do with the datatypes we have
  4.  
  5. ### List
  6.  
  7. Let's start with a simple program:
  8. ```Java
  9. public class Sets {
  10. public static void main(String[] args) {
  11. Set<Integer> a = new HashSet<Integer>();
  12. Set<Integer> b = new HashSet<Integer>();
  13.  
  14. a.addAll(Arrays.asList(2,4,6,8,10));
  15. b.addAll(Arrays.asList(1,2,3,4,5));
  16.  
  17. System.out.println("A: "+a);
  18. System.out.println("B: "+b);
  19. }
  20. }
  21. ```
  22. ---
  23. What is a union?
  24.  
  25. Can we find the union between two Lists?
  26.  
  27. ```Java
  28. Set<Integer> union = new HashSet<Integer>();
  29. union.addAll(a);
  30. union.addAll(b);
  31. System.out.println("Union: "+union);
  32. ```
  33.  
  34. The set will have the combined value of the lists.
  35.  
  36. ---
  37.  
  38. What is an intersection?
  39.  
  40. What is the intersection of two lists?
  41. ---
  42.  
  43. ```Java
  44. Set<Integer> intersection = new HashSet<Integer>();
  45. intersection.addAll(a);
  46. intersection.retainAll(b);
  47. System.out.println("Intersection: "+intersection);
  48. ```
  49. ---
  50. What is a difference?
  51.  
  52. What is the difference between the two lists?
  53. ---
  54.  
  55. ```Java
  56. Set<Integer> difference = new HashSet<Integer>();
  57. difference.addAll(a);
  58. difference.removeAll(b);
  59. System.out.println("Difference: " + difference);
  60. ```
  61.  
  62. ---
  63. What is the complement?
  64.  
  65. What is the complement between the two lists?
  66. ---
  67.  
  68. ```Java
  69. Set<Integer> complement = new HashSet<Integer>();
  70. complement.addAll(B);
  71. complement.removeAll(A);
  72. System.out.println("Complement: " + complement);
  73. ```
  74. ---
  75. Sieve Of Eratosthenes
  76.  
  77. What is it?
  78. It is a fast way of finding primes. In the original Greek, `κόσκινον Ἐρατοσθένους` it was found by Eratosthenes of Cyrene.
  79.  
  80. ---
  81. ```Java
  82. public class SieveOfEratosthenes {
  83.  
  84. public static List<Integer> calculate(int n) {
  85.  
  86. boolean[] prime = new boolean[n + 1];
  87.  
  88. List<Integer> list = new ArrayList<Integer>();
  89. for (int i = 2; i < n; i++) {
  90. prime[i] = true;
  91. }
  92. for (int i = 2; i < n; i++) {
  93. if (prime[i]) {
  94. list.add(i);
  95. for (int j = i; j * i <= n; j++) {
  96. prime[i * j] = false;
  97. }
  98. }
  99. }
  100. return list;
  101. }
  102.  
  103. public static void main(String[] args) {
  104. List<Integer> list = calculate(100);
  105. for (Integer prime : list) {
  106. System.out.println(prime);
  107. }
  108. }
  109. }
  110. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement