Search code examples
javastringlistjava-stream

Filter two lists that have same elements to only obtain a list with distinct elements using Java Stream


I have list1 and list2 like below

List<String> list1 = List.of("DX4555", "DY4897", "FG4333", "IH09992");
List<String> list2 = List.of("DX4555", "DY4897", "FG4333", "IH09992", "LJ48833", "YTR3888");

What I would like to achieve is to have a list that only contains elements in list2 that are not in list1 which are unique which are ["LJ48833","YTR3888"]

I would like to achieve this using Java Stream

I have tried using stream().distinct(), but it's not working.


Solution

  • Stream.distinct() only allows you to discard elements that are present multiple times in the same collection or as they are iterated.

    I suggest using ListUtils.subtract from apache commons, but you can also do it with streams, like this:

    List<String> result = list2.stream()
    .filter(item -> !list1.contains(item))
    .collect(Collectors.toList());
    

    Notice that it's an O(n^2) algorithm, due to the fact that List.contains is linear. If your lists are big, you should replace them with sets to be more efficient.