0

I have 2 collections as shown below

List<TestSVM> listOne = new ArrayList<TestSVM>();
// TODO: Add sample data to listOne.
listOne.add(new TestSVM("nameA", "school1"));
listOne.add(new TestSVM("nameC", "school2"));
listOne.add(new TestSVM("nameB", "school3"));

List<TestSVM> listTwo = new ArrayList<TestSVM>();
listTwo.add(new TestSVM("nameA", "school1"));
listTwo.add(new TestSVM("nameC", "school2"));

I need to use Java stream filter to get the list of objects from listOne that does not have matching school name in listTwo. In this case the result should be a List of size 1 with object

("nameB", "school3")

I used this filter statement, but not getting result as expected. I am getting the entire listOne as result.

List<TestSVM> results = listOne.stream().filter(one-> listTwo.stream()
              .anyMatch(two -> !two.getSchool().equals(one.getSchool()))) 
              .collect(Collectors.toList());

However, I also observed that when the size of listTwo is 1 (only), the result is as expected, I just get the list of objects in listOne that are not part of listTwo

Please help with the Streams filter statement to achieve the same.

vigneshr35
  • 77
  • 2
  • 12

1 Answers1

0

Negation should be inside filter, since anyMatch returns true if at least one match found

List<TestSVM> results = listOne.stream().filter(one-> !listTwo.stream()
          .anyMatch(two -> two.getSchool().equals(one.getSchool()))) 
          .collect(Collectors.toList());
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98