yangxu998 / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Add a version of Maps.difference that takes an Equivalence to determine map value equality #640

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
The signature would like like this:

public static <K, V> MapDifference<K, V> difference(Map<? extends K, ? extends 
V> left, Map<? extends K, ? extends V> right, Ordering<? super V> ordering)

and only one line would change. Replace

Objects.equals(leftValue,rightValue), 

with 

ordering.compare(leftValue,rightValue)==0

Many objects define equals() based on a "business key." But to accurately 
determine MapDifference.entriesDiffering(), these objects should be compared 
using a deep-equals. 

Here is a common use-case: syncing persisted entities. Suppose we have a 
collection of persisted User entities and a collection of un-persisted User 
entities. We want to determine which entities to insert, which to delete, and 
which to update.

Suppose User defines equality based on a unique String userName. If we map the 
collections by their unique userName, Maps.difference will determine which 
persisted entities to delete and which new entities to insert but not 
necessarily which ones to update. MapDifference.entriesInCommon() will contain 
both unchanged entries and entries that differ in value. 
MapDifference.entriesDiffering() will be empty.

I realize that the validity of allowing the caller to specify a custom equality 
has been debated before (see issue 188) but I think in this case it can add a 
lot of value.

Original issue reported on code.google.com by ori.schw...@gmail.com on 5 Jun 2011 at 3:33

GoogleCodeExporter commented 9 years ago
Sorry I didn't notice that Guava has an Equivalence interface, obviously in my 
comment above that should be used instead of an Ordering.

new signature looks like:

public static <K, V> MapDifference<K, V> difference(Map<? extends K, ? extends 
V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> 
equivalence)

and Objects.equals(leftValue,rightValue) should be replaced with 
equivalence.equivalent(leftValue,rightValue)

Original comment by ori.schw...@gmail.com on 7 Jun 2011 at 12:57

GoogleCodeExporter commented 9 years ago

Original comment by cpov...@google.com on 22 Jun 2011 at 6:24

GoogleCodeExporter commented 9 years ago

Original comment by cpov...@google.com on 22 Jun 2011 at 7:07

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:15

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:09