Assume two lists:
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
Elements in list1 but not in list2
List<Integer> difference = list1.stream()
.filter(e -> !list2.contains(e))
.collect(Collectors.toList());
System.out.println(difference);
Output:
[1, 2]
Summary:
.filter(e -> !list2.contains(e))keeps elements only in the first list..collect(Collectors.toList())returns the result as a new list.- For large lists, converting
list2to aSetimproves performance.
