gogoWebsite

How to implement the sorting of custom class key values ​​in TreeMap

Updated to 19 days ago

In TreeMap, if the key value is the basic type in Java, TreeMap will sort it for us. If it is a custom type, if we define a Student class as the key value, if we do not inform the sorting rules, we will report an error when running. So, how to implement custom sorting? There are 2 solutions, just choose one of them:

Implement Comparable in Student class and override the compareTo method
In the constructor, new Comparator, anonymous internal class, override the compare method
 

TreeMap<String,List<ZTreeDTO>> retultMap = new TreeMap<String,List<ZTreeDTO>>(new Comparator<String>(){
			@Override
			public int compare(String o1, String o2) {
				o1 = getTypeByProjectName(o1);
            	o2 = getTypeByProjectName(o2);
                return  (o2);
			}
        });