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

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

    I will do something like this:

    List order = List.of("Red", "Green", "Magenta", "Silver");
    
    Comparator.comparing(Car::getColor(), Comparator.comparingInt(c -> order.indexOf(c)))
    

    All credits go to @Sean Patrick Floyd :)

提交回复
热议问题