In: Computer Science
Method: ArrayList<Integer> diff(ArrayList<Integer> list1, ArrayList<Integer> list2) diff() method accepts two ArrayLists of Integer and returns the union of elements in two lists. For example: list1 contains elements [1, 2, 3, 4, 5] list2 contains elements [3, 4, 5, 6, 7] Diff() method should return an array list with elements [1, 2, 3, 4, 5, 6, 7].
import java.util.ArrayList; import java.util.Arrays; public class UnionArrayLists { public static ArrayList<Integer> diff(ArrayList<Integer> list1, ArrayList<Integer> list2) { ArrayList<Integer> result = new ArrayList<>(); for (int i = 0; i < list1.size(); i++) { if (!result.contains(list1.get(i))) { result.add(list1.get(i)); } } for (int i = 0; i < list2.size(); i++) { if (!result.contains(list2.get(i))) { result.add(list2.get(i)); } } return result; } public static void main(String[] args) { ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7)); System.out.println(diff(list1, list2)); } }