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

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

问题描述

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

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天全站免登陆