Note that there are some explanatory texts on larger screens.

plurals
  1. POCompare two Java Collections using Comparator instead of equals()
    primarykey
    data
    text
    <h1>Problem Statement</h1> <p>I have two Collections of the same type of object that I want to compare. In this case, I want to compare them based on an attribute that does not factor into <code>equals()</code> for the Objects. In my example, I'm using ranked collections of Names for instance:</p> <pre><code>public class Name { private String name; private int weightedRank; //getters &amp; setters @Override public boolean equals(Object obj) { return this.name.equals(obj.name); //Naive implementation just to show //equals is based on the name field. } } </code></pre> <p>I want to compare the two Collections to assert that, for position <code>i</code> in each Collection, the <code>weightedRank</code> of each Name at that position is the same value. I did some Googling but didn't find a suitable method in Commons Collections or any other API so I came up with the following:</p> <pre><code>public &lt;T&gt; boolean comparatorEquals(Collection&lt;T&gt; col1, Collection&lt;T&gt; col2, Comparator&lt;T&gt; c) { if (col1 == null) return col2 == null; if (col2 == null) return false; if (col1.size() != col2.size()) return false; Iterator&lt;T&gt; i1 = col1.iterator(), i2 = col2.iterator(); while(i1.hasNext() &amp;&amp; i2.hasNext()) { if (c.compare(i1.next(), i2.next()) != 0) { return false; } } return true; } </code></pre> <h1>Question</h1> <p>Is there another way to do this? Did I miss an obvious method from Commons Collections?</p> <h1>Related</h1> <p>I also spotted <a href="https://stackoverflow.com/questions/11758220/a-mechanism-for-having-different-equals-physical-equals-and-logical-equals-on">this question</a> on SO which is similar though in that case I'm thinking overriding <code>equals()</code> makes a little more sense.</p> <h2>Edit</h2> <p>Something very similar to this will be going into a release of <a href="http://commons.apache.org/proper/commons-collections/" rel="nofollow noreferrer">Apache Commons Collections</a> in the near future (at the time of this writing). See <a href="https://issues.apache.org/jira/browse/COLLECTIONS-446" rel="nofollow noreferrer">https://issues.apache.org/jira/browse/COLLECTIONS-446</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload