Sobes.tech
Senior

Task: Given two lists, output the elements of the first list that are not in the second. Write a solution in Java.

sobes.tech AI

Answer from AI

To solve the problem, you can use a HashSet collection for quick lookup of elements from the second list and then filter the first list. Here's an example in Java:

import java.util.*;

public class ListDifference {
    public static <T> List<T> difference(List<T> list1, List<T> list2) {
        Set<T> set2 = new HashSet<>(list2);
        List<T> result = new ArrayList<>();
        for (T item : list1) {
            if (!set2.contains(item)) {
                result.add(item);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> list2 = Arrays.asList(3, 4, 6);
        List<Integer> diff = difference(list1, list2);
        System.out.println(diff); // Outputs [1, 2, 5]
    }
}

This approach is efficient in terms of time, as lookup in a set occurs in O(1) on average.

Task: Given two lists, output the elements of the… - sobes.tech