Java – use TreeSet for sorting without providing comparator
I know that TreeSet in Java will automatically sort its elements in ascending order to ensure the order
For example, if I have a random array of date objects and copy it to TreeSet, it will be added to TreeSet in an orderly manner
But suppose I have an ArrayList of HashMap < string, Object > instead of a simple Date object, using the following format
The first value of ArrayList,
{mydate = 32156464,mystring = "abc",mystring2 = "xyz"}
翻译错误 TIMEOUT
{mydate = 64687678,mystring = "abdc",mystring2 = "xyzzz"}
The third value in the ArrayList of HashMap,
{mydate = 11233678,mystring = "abxdc",mystring2 = "xyzppzz"}
Now, if I want to sort the ArrayList of this HashMap based on the mydate key, I must create a new comparator in the TreeSet instance, as shown below,
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 ArrayList in TreeSet in sort order But I use a custom comparator to achieve this goal If I'm still providing a custom comparator for it, what's the point of using TreeSet to sort the data in this case?
How to sort the ArrayList of HashMap according to the date value without using the new instance of comparator in TreeSet?
Solution
Because it is TreeSet code, it keeps sorting You don't have to provide any code - you have to provide a custom comparison
You can't, directly You can write a subclass of HashMap that implements comparable for yourself, but it seems strange 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 can have an ArrayList < specialmap > and sort it
However, since you must provide basically the same code as the comparator and bind your comparison to the map type, I think it's best to just stick to the comparator