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

后端 未结 9 1001
生来不讨喜
生来不讨喜 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:23

    I think this can be done as follows:

    class ColorComparator implements Comparator
    {
        private List sortOrder;
        public ColorComparator (List sortOrder){
            this.sortOrder = sortOrder;
        }
    
        public int compare(CarSort c1, CarSort c2)
        {
            String a1 = c1.getColor();
            String a2 = c2.getColor();
            return sortOrder.indexOf(a1) - sortOrder.indexOf(a2);
         }
     }
    

    For sorting use this:

    Collections.sort(carList, new ColorComparator(sortOrder));
    

提交回复
热议问题