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
The problem is complex, but it boils down to one thing, know your data. Is it imutables, entities with an id, duplicate entries etc? The code below works for immutables with only values (and with possible duplicates). It first tries to remove all entries in the before list (from the copied after-list). What is left will be the added elements. The ones from the before-list that can be removed from the after-list are the unchanged ones. The rest are the removed ones
package scrap;
import java.util.ArrayList;
import java.util.List;
public class ListDiffer<T> {
private List<T> addedList = new ArrayList<>();
private List<T> unchangedList = new ArrayList<>();
private List<T> removedList = new ArrayList<>();
public ListDiffer(List<T> beforeList, List<T> afterList) {
addedList.addAll(afterList); // Will contain only new elements when all elements in the Before-list are removed.
beforeList.forEach(e -> {
boolean b = addedList.remove(e) ? unchangedList.add(e) : removedList.add(e);
});
}
public List<T> getAddedList() {
return addedList;
}
public List<T> getUnchangedList() {
return unchangedList;
}
public List<T> getRemovedList() {
return removedList;
}
}
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());