0

I have two ArrayList of String with list of ID.

List list1 -> ["1", "2", "3," "4", "5", "6"] and List list2 -> ["2", "3," "4", "6"]

I want to get a list of ID not repeated.

List list3 -> ["1", "5"]

I've developed this with Java 7:

for (String id : list1) {
   if (!list2.contains(id)) {
     list3.add(id);
   }
 }

I want to do this in Java functional programming... is possible using streams or similar?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
davidleongz
  • 155
  • 2
  • 11

2 Answers2

1

As pointed out in the comments, the correct (as in "more readable", "more idiomatic" and "less error-prone") way to do this is to use removeAll, as in

list1.removeAll(list2);

Note that this modifies the original list.

If you insist on using streams (or simply you don't want to modify the original list) you can filter out values that appear in both lists (i.e. letting only values from list1 that are not contained in list2 past the filter)

var list3 = list1.stream()
                 .filter(Predicate.not(list2::contains))
                 .collect(Collectors.toList());

Note: I used Predicate::not since you tagged the question with java-11. It's not available in Java 8. If you are stuck with Java 8 (or 9, or 10) the process is similar if a little more verbose

var list3 = list1.stream()
                 .filter(s -> !list2.contains(s))
                 .collect(Collectors.toList());
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
0

Yes

List<String> differences = listOne.stream()
            .filter(element -> !listTwo.contains(element))
            .collect(Collectors.toList());

Source: https://www.baeldung.com/java-lists-difference

Jeremy Dsilva
  • 71
  • 1
  • 4