Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the difference between two collections in Java 8?

I am trying to make a List of all of the books in one Collection that are not present in another. My problem is that I need to compare based on book ID, so I can't just test to see whether a book in the first is contained in the second, I have to determine whether any book in the second collection has the same ID as a book in the first.

I have the below code to compare two collections of books and filter the first collection:

List<Book> parentBooks = listOfBooks1.stream().filter(book->   !listOfBooks2.contains(book)).collect(Collectors.toList()); 

The code doesn't work correctly because I am comparing the objects themselves. I need to compare the objects based on the bookId instead of the whole book object. How should I change the code so it can do the comparison based on the bookId (book.getId())?

like image 873
Nisman Avatar asked Jul 06 '16 14:07

Nisman


People also ask

How do I compare two lists in Java and get differences?

Using the Java List API. We can create a copy of one list and then remove all the elements common with the other using the List method removeAll(): List<String> differences = new ArrayList<>(listOne); differences. removeAll(listTwo); assertEquals(2, differences.

How do I compare two lists in Java?

Java provides a method for comparing two Array List. The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.


1 Answers

List<Book> books1 = ...; List<Book> books2 = ...; Set<Integer> ids = books2.stream()         .map(Book::getId)         .collect(Collectors.toSet()); List<Book> parentBooks = books1.stream()         .filter(book -> !ids.contains(book.getId()))         .collect(Collectors.toList()); 
like image 195
Sergii Lagutin Avatar answered Oct 13 '22 01:10

Sergii Lagutin