1

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?

1
  • 5
    Why not just do list1.removeAll(list2) instead of loops or streams? Commented Jan 26, 2022 at 12:36

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

Comments

0

Yes

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.