Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Java Data Types Structures and Operations
- ## Let see what we can do with the datatypes we have
- ### List
- Let's start with a simple program:
- ```Java
- public class Sets {
- public static void main(String[] args) {
- Set<Integer> a = new HashSet<Integer>();
- Set<Integer> b = new HashSet<Integer>();
- a.addAll(Arrays.asList(2,4,6,8,10));
- b.addAll(Arrays.asList(1,2,3,4,5));
- System.out.println("A: "+a);
- System.out.println("B: "+b);
- }
- }
- ```
- ---
- What is a union?
- Can we find the union between two Lists?
- ```Java
- Set<Integer> union = new HashSet<Integer>();
- union.addAll(a);
- union.addAll(b);
- System.out.println("Union: "+union);
- ```
- The set will have the combined value of the lists.
- ---
- What is an intersection?
- What is the intersection of two lists?
- ---
- ```Java
- Set<Integer> intersection = new HashSet<Integer>();
- intersection.addAll(a);
- intersection.retainAll(b);
- System.out.println("Intersection: "+intersection);
- ```
- ---
- What is a difference?
- What is the difference between the two lists?
- ---
- ```Java
- Set<Integer> difference = new HashSet<Integer>();
- difference.addAll(a);
- difference.removeAll(b);
- System.out.println("Difference: " + difference);
- ```
- ---
- What is the complement?
- What is the complement between the two lists?
- ---
- ```Java
- Set<Integer> complement = new HashSet<Integer>();
- complement.addAll(B);
- complement.removeAll(A);
- System.out.println("Complement: " + complement);
- ```
- ---
- Sieve Of Eratosthenes
- What is it?
- It is a fast way of finding primes. In the original Greek, `κόσκινον Ἐρατοσθένους` it was found by Eratosthenes of Cyrene.
- ---
- ```Java
- public class SieveOfEratosthenes {
- public static List<Integer> calculate(int n) {
- boolean[] prime = new boolean[n + 1];
- List<Integer> list = new ArrayList<Integer>();
- for (int i = 2; i < n; i++) {
- prime[i] = true;
- }
- for (int i = 2; i < n; i++) {
- if (prime[i]) {
- list.add(i);
- for (int j = i; j * i <= n; j++) {
- prime[i * j] = false;
- }
- }
- }
- return list;
- }
- public static void main(String[] args) {
- List<Integer> list = calculate(100);
- for (Integer prime : list) {
- System.out.println(prime);
- }
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement