How do I use Comparator to define a custom sort order?

后端 未结 9 1106
生来不讨喜
生来不讨喜 2020-11-22 08:40

I want to develop a sorting demo for car list. I am using data table to display car list. Now actually I want to sort the list by car color. Here it is not sort by alphabeti

9条回答
  •  野性不改
    2020-11-22 09:27

    I had to do something similar to Sean and ilalex's answer.
    But I had too many options to explicitly define the sort order for and only needed to float certain entries to the front of the list ... in the specified (non-natural) order.
    Hopefully this is helpful to someone else.

    public class CarComparator implements Comparator {
    
        //sort these items in this order to the front of the list 
        private static List ORDER = Arrays.asList("dd", "aa", "cc", "bb");
    
        public int compare(final Car o1, final Car o2) {
            int result = 0;
            int o1Index = ORDER.indexOf(o1.getName());
            int o2Index = ORDER.indexOf(o2.getName());
            //if neither are found in the order list, then do natural sort
            //if only one is found in the order list, float it above the other
            //if both are found in the order list, then do the index compare
            if (o1Index < 0 && o2Index < 0) result = o1.getName().compareTo(o2.getName());
            else if (o1Index < 0) result = 1;
            else if (o2Index < 0) result = -1;
            else result = o1Index - o2Index;
            return result;
        }
    
    //Testing output: dd,aa,aa,cc,bb,bb,bb,a,aaa,ac,ac,ba,bd,ca,cb,cb,cd,da,db,dc,zz
    }
    

提交回复
热议问题