-1

There are 2 lists containing some string elements. These lists may be equal or there may be some missing elements in second list.

The task is to compare these 2 lists and to find a missing emlenet or missing elements in second list and print them.

IgorPiven
  • 11
  • 4
  • Copy the first (the complete) list using `new ArrayList<>(list1)`. From the copy delete elements that are also in the other list using the `removeAll()` method passing `list2` as argument. Now the copy contains the missing element or elements -- or is empty if there weren’t any. – Ole V.V. Feb 27 '23 at 11:47
  • Does this answer your question? [How can I return the difference between two lists?](https://stackoverflow.com/questions/27002882/how-can-i-return-the-difference-between-two-lists) – Ole V.V. Feb 27 '23 at 11:59
  • What is your expected result is a string occurs more than once in either of the lists? Say, 3 times in the complete list and only twice in the second list. Or three times in the complete list and not at all in the second list. – Ole V.V. Feb 27 '23 at 12:55

2 Answers2

1

You could try something like that:

public static List<String> ListDiff(List<String> a, List<String> b) {
    return a.stream()
            .filter(s->!b.contains(s))
            .collect(Collectors.toList());
}

But note that if you were using Sets instead of Lists, you could use removeAll that would probably be much faster.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
-1

Basically, you need to check if each element of list 1 is in list 2 or not. It it's present, do nothing. If it's not, print it. I'm gonna solve this problem using python as that's what I'm good at haha.

Let us say your first list is ['A', 'B', 'C'] and the second list is ['A', 'B']. Then,

list1 = ['A', 'B', 'C']
list2 = ['A', 'B', 'C']
if list1 == list2:
    print("Equal lists")
else:
    for i in list1:
        if i not in list2:
            print(i)