Write a java program for ArrayList and Set Operations.

Write a program that performs the following actions:

  1. Read 2n integers as input & a set operator (of type char).
  2. Create two arraylists to store n elements in each arraylist.
  3. Write a function  performSetOperations which accepts these two arraylist and the set operator as input.
  4. The function would perform the following set operations:.’+’ for SET-UNION

    ‘*’ for SET-INTERSECTION

    ‘-‘ for SET-DIFFERENCE

    Refer to sample inputs for more details.

5.    Return the resultant arraylist.
Include a class UserMainCode with the static method performSetOperations which accepts two arraylist and returns an array list.

Create a Class Main which would be used to read 2n+1 integers and call the static method present in UserMainCode.

Note:

– The index of the first element is 0.

Input and Output Format:

Input consists of 2n+2 integers. The first integer denotes the size of the array list, the next n integers are values to the first array list, and the next n integers are values to the second array list and the last input corresponds to that set operation type.

The output consists of a modified ArrayList as per step 4.

Refer sample output for formatting specifications.

Sample Input 1:

3

1

2

3

3

5

7

+

Sample Output 1:

1

2

3

5

7

Sample Input 2:

4

10

9

8

7

2

4

6

8

*

Sample Output 2:

8

Sample Input 3:

4

5

10

15

20

0

10

12

20

Sample Output 3:

5

15

Set Operations in Java.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int n = Integer.parseInt(sc.nextLine());
    ArrayList<Integer> a1 = new ArrayList<Integer>();
    ArrayList<Integer> a2 = new ArrayList<Integer>();
    for (int i = 0; i < n; i++)
      a1.add(Integer.parseInt(sc.nextLine()));
    for (int i = 0; i < n; i++)
      a2.add(Integer.parseInt(sc.nextLine()));
    char c = sc.nextLine().charAt(0);
    System.out.println(getvalues(a1, a2, c));

  }

  public static ArrayList<Integer> getvalues(ArrayList<Integer> a1,
      ArrayList<Integer> a2, char c) {
    ArrayList<Integer> op1 = new ArrayList<Integer>();
    int k = 0;
    switch (c) {
    case '+':
      a1.removeAll(a2);
      a1.addAll(a2);
      op1 = a1;
      break;
    case '*':
      a1.retainAll(a2);
      op1 = a1;
      break;
    case '-':
      for (int i = 0; i < a1.size(); i++) {
        k = 0;
        for (int j = 0; j < a2.size(); j++) {
          if (a1.get(i) == a2.get(j))
            k = 1;
        }
        if (k == 0)
          op1.add(a1.get(i));
      }
      break;
    }
    return op1;
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

2 × one =