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

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

    In Java 8 you can do something like this:

    You first need an Enum:

    public enum Color {
        BLUE, YELLOW, RED
    }
    

    Car class:

    public class Car {
    
        Color color;
    
        ....
    
        public Color getColor() {
            return color;
        }
    
        public void setColor(Color color) {
            this.color = color;
        }
    }
    

    And then, using your car list, you can simply do:

    Collections.sort(carList, Comparator:comparing(CarSort::getColor));
    

提交回复
热议问题