如何使用 Comparator 定义自定义排序顺序? [英] How do I use Comparator to define a custom sort order?

查看:33
本文介绍了如何使用 Comparator 定义自定义排序顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为汽车列表开发一个排序演示.我正在使用数据表来显示汽车列表.现在实际上我想按汽车颜色对列表进行排序.这里不是按字母顺序排序的.我想使用我的自定义排序顺序,例如红车先到,然后是蓝车,等等.

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 alphabetic order. I want to use my custom sorting order like Red car come first, then Blue, etc.

为此,我尝试使用 Java 比较器可比较 但它只允许按字母顺序排序.

For that I try to use Java Comparator and Comparable but it allows to sort in alphabetic order only.

那么,谁能指导我实现要使用的技术的方法,以便排序变得更快.

So, can any one guide me the way to implement the technique to use so that the sorting becomes faster.

class Car implements Comparable<Car>
{
    private String name;
    private String color;

    public Car(String name, String color){
        this.name = name;
        this.color = color;
    }

    //Implement the natural order for this class
    public int compareTo(Car c) {
        return name.compareTo(c.name);
    }

    static class ColorComparator implements Comparator<Car> {
        public int compare(Car c1, Car c2) {
            String a1 = c1.color;
            String a2 = c2.color;
            return a1.compareTo(a2);
        }
    }

    public static void main(String[] args) {
        List<Car> carList = new ArrayList<>();
        List<String> sortOrder = new ArrayList<>();

        carList.add(new Car("Ford","Silver"));
        carList.add(new Car("Tes","Blue"));
        carList.add(new Car("Honda","Magenta"));

        sortOrder.add("Silver");
        sortOrder.add("Magenta");
        sortOrder.add("Blue");

        // Now here I am confuse how to implement my custom sort             
    }
}

推荐答案

我建议您为汽车颜色创建一个枚举,而不是使用字符串,并且枚举的自然顺序将是您声明常量的顺序.

I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

public enum PaintColors {
    SILVER, BLUE, MAGENTA, RED
}

 static class ColorComparator implements Comparator<CarSort>
 {
     public int compare(CarSort c1, CarSort c2)
     {
         return c1.getColor().compareTo(c2.getColor());
     }
 }

您将字符串更改为 PaintColor,然后在主汽车列表中变为:

You change the String to PaintColor and then in main your car list becomes:

carList.add(new CarSort("Ford Figo",PaintColor.SILVER));

...

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

这篇关于如何使用 Comparator 定义自定义排序顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆