using TreeSet to sort without providing a Comparator to it

I know that TreeSet in java automatically sort its elements in ascending order an it guarantees the order.

for example, If i have an array of Date object in random and I copy it to TreeSet then it will be added in TreeSet in sorted way.

but suppose instead of a simple Date object, I have an ArrayList of HashMap<String,Object>, in the following format.

first value in arraylist,

{mydate = 32156464 , mystring = "abc", mystring2 = "xyz"}

2nd value in arraylist of hashmap,

{mydate = 64687678 , mystring = "abdc", mystring2 = "xyzzz"}

3rd value in arraylist of hashmap,

{mydate = 11233678 , mystring = "abxdc", mystring2 = "xyzppzz"}

Now if i want to sort this arraylist of hashmap based on mydate key, i have to create a new comparator in TreeSet instance like this,

public static Set<HashMap<String, Object>> mySet = new TreeSet<>(new Comparator<HashMap<String, Object>>() {
        @Override
        public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
            return ((Date) o2.get(mydate)).compareTo((mydate) o1.get(DATE));
        }
    }); 

and it will store the arraylist inside the TreeSet in sorted order just fine. But I have used a custom Comparator to achieve this. What is the point of using TreeSet in this situation for sorting data if i am also providing a custom Comparator to it ?

How can i sort this ArrayList of HashMap based on date value without using a new instance of Comparator in TreeSet ?

Jon Skeet
people
quotationmark

What is the point of using TreeSet in this situation for sorting data if i am also providing a custom Comparator to it ?

Because it's the TreeSet code that keeps it sorted. You haven't had to provide any of the code for that - all you've had to provide is the custom comparison.

How can i sort this ArrayList of HashMap based on date value without using a new instance of Comparator in TreeSet ?

You can't, directly. You could write a subclass of HashMap which implemented Comparable for itself, but that would seem a bit odd to me. For example:

public class SpecialMap extends HashMap<String, Object>
    implements Comparable<SpecialMap> {

    private final String key;

    public SpecialMap(String key) {
        this.key = key;
    }

    public int compareTo(SpecialMap other) {
        // TODO: Null handling
        Date thisDate = (Date) this.get(key);
        Date otherDate = (Date) other.get(key);
        return thisDate.compareTo(otherDate);
    }
}

Then you could have an ArrayList<SpecialMap> and sort that.

But given that you've had to provide basically the same code as for the comparator and bound your comparison with the map type, it feels to me like it would be better just to stick with the comparator.

people

See more on this question at Stackoverflow