以特定顺序对(数组)列表进行排序 [英] Sort an (Array)List with a specific order

查看:35
本文介绍了以特定顺序对(数组)列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,我想按定义的顺序对其进行排序.例如.我有一个带有 String color 字段的对象.我想在颜色字段上对我的列表进行排序,以便它始终首先是白色,而不是蓝色,而不是黄色,然后是所有其他(如果可能,已排序但不是必需的):

I have a list of objects and I would like to sort it with a defined order. For ex. I have an object with a field String color. I would like to sort my list on the color field so that it always has first white than blue than yellow and than all the others(if possible alph. ordered but not necessary):

Before sorting:         After sorting:
orange                  white
white                   blue
green                   yellow
brown                   orange
yellow                  black
black                   brown
...                     ...

有没有(简单的)方法可以做到这一点?

Is there a (easy) way to do that?

我必须添加更多复杂功能...
如果可以有更多具有相同名称/基数的颜色怎么办?例如.whiteX, whiteY, whiteZ, blueA, blueB, ...
所有的白人都必须先于所有的蓝人,而不是所有的黄种人和其他人.仍然可以用比较器解决这个问题吗?(我无法想象怎么...)

I have to add a complication more...
What if there can be more colors with the same name/radix? For ex. whiteX, whiteY, whiteZ, blueA, blueB, ...
All the whites must come first than all the blues than all the yellows and than all the others. It is still possible to solve that with a comparator? (I can't imagine how...)

推荐答案

是的,您可以创建一个 比较器 用于创建您的排序策略,或定义您的类的自然顺序实现比较

Yes you can create a Comparator for creating your sort strategy, or define natural-order of your class implementing Comparable

附注:

强烈推荐,但不严格要求(x.compareTo(y)==0) == (x.equals(y))

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))

使用比较器的示例:

class MyClass {

private Color color;
private String someOtherProperty;
public static final Comparator<MyClass> COLOR_COMPARATOR = new MyComparator();

//getter and setter

static class MyComparator implements Comparator<MyClass>{

            @Override
            public int compare(MyClass o1, MyClass o2) {
                // here you do your business logic, when you say where a color is greater than other
            }    
}

}

在客户端代码中.

示例:

List<MyClass> list = new ArrayList<>();
//fill array with values
Collections.sort(list, MyClass.COLOR_COMPARATOR );

阅读更多:Collections#sort(..)

如果您想定义类的自然顺序,只需定义

If you want to define natural-ordering of your class just define

public class MyClass implements Comparable<MyClass>{

        @Override
        public int compareTo(MyClass o) {
           // do business logic here
        }
}

在客户端代码中:

   Collections.sort(myList); // where myList is List<MyClass>

这篇关于以特定顺序对(数组)列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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