Manu Joy
Manu Joy

Reputation: 1769

Minus operation in java 8 for subtracting Lists

Suppose I have two lists:

List<Integer> list1 =  Arrays.asList(1, 2, 3);
List<Integer> list2 =  Arrays.asList(1, 2, 4, 5);

Now I want to perform (list1 - list2). The expected ouptut is {3}. How to do this using java 8 streams?

Upvotes: 12

Views: 25661

Answers (3)

Eran
Eran

Reputation: 393846

If you must use Streams:

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

Upvotes: 24

Hiren
Hiren

Reputation: 1435

Try this:

List<Integer> difference = new ArrayList<>(list1);
difference.removeAll(list2);
System.out.println("Remove: " + difference); //3

Upvotes: 13

Igal
Igal

Reputation: 51

Using Apache commons:

CollectionUtils.subtract(list1, list2);

Pros: Very readable. Cons: No type safety

Upvotes: 5

Related Questions