I have 2 lists coming into my method sorted in a certain order (either ascending or descending based on an ID field)
I have a custom comparator implementation that allows me to throw both lists into the treeset and achieve the desired results.
My issue is after the treeset is loaded, I need to return a single list back from the method. My first implementation didn’t care about ordering so I did this (composite is my named TreeSet):
composite.addAll(custom);
composite.addAll(reference);
Iterator<MyObject> anIter = composite.iterator();
ArrayList<MyObject> returnVal = new ArrayList<MyObject>();
while(anIter.hasNext())
returnVal.add(anIter.next());
Once I execute this, the two lists “custom” and “reference” are back to the default ordering. The Javadocs for Collection’s iterator() method state that will return the list in ascending order, which is likely where my trouble is coming from.
So…is there no way to return the content of a TreeSet while protecting the original list ordering? A treeset is what came to mind because I wanted to use the power of the comparator interface over the two collections to union them with addAll() and throw out the dupes.
Any suggestions on protecting the ordering would be appreciated.
EDIT*
Set<MyObject> composite = new TreeSet<MyObject>(new Comparator<MyObject>(){
@Override
public int compare(MyObject arg0, MyObject arg1) {
int arg0ID = arg0.getObjID();
int arg1ID = arg1.getObjID();
if(arg0ID < arg1ID) return -1;
else if(arg0ID> arg1ID) return 1;
else return 0;
}
});
No, of course not.
TreeSetis the wrong tool for this job. The point of using aTreeSetis that it applies aComparator-based ordering on the objects that the set contains. Use a different data structure — how about aLinkedHashSet? — if you want to remove duplicate objects while retaining insertion order.In a
TreeSet: “The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.” You cannot pick any order ordering (particularly one like insertion ordering) with aTreeSet. If you can’t useequals()andhashCode()to pick the object fields that represent identity, use a decorate-dedup-undecorate pattern with aLinkedHashSet, where the decorator containsequals()andhashCode()implementations.Comparator/Comparableis for specifying ordering, not identity or equality.Yes, exactly. Either make
MyObjectimplement the.equals()and.hashCode()that you mean:and dedup like so:
Or use the decorate–dedup–undecorate pattern that I mentioned. The decorator class would look something like this:
and here’s roughly how you’d use it: