HashingStrategy is the concept you are looking for. This is a strategy interface that allows you to define custom implementations of equals and hashcode.
public interface HashingStrategy<E> { int computeHashCode(E object); boolean equals(E object1, E object2); }
Eclipse Collections includes hash tables as well as iteration patterns based on hash strategies. First, you must create your own HashingStrategy to answer if the two Books are equal.
You can then use distinct() to remove duplicates in newBooks and UnifiedSetWithHashingStrategy to eliminate duplicates in lists.
List<Book> oldBooks = ...; List<Book> newBooks = ...; HashingStrategy<Book> hashingStrategy = new HashingStrategy() { ... }; Set<Book> set = UnifiedSetWithHashingStrategy<>(hashingStrategy, oldBooks); List<Book> result = ListIterate.distinct(newBooks, hashingStrategy).reject(set::contains);
The distinct() method returns only unique elements according to the hashing strategy. It returns a list, not a set, preserving the original order. The reject() call returns another new list without the elements that the collection contains, in accordance with the same hashing strategy.
If you can change newBooks to implement the Eclipse Collections interface, you can directly call the distinct() method.
MutableList<Book> newBooks = ...; MutableList<Book> result = newBooks.distinct(hashingStrategy).reject(oldBooks::contains);
Note. I am a committer for Eclipse collections.
source share