按特定顺序对(Array)List进行排序 [英] Sort an (Array)List with a specific order

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

问题描述

我有一个对象列表,我想按定义的顺序对其进行排序. 对于前.我有一个字段为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...)

推荐答案

是的,您可以创建自然顺序. com/javase/7/docs/api/java/lang/Comparable.html"rel =" nofollow noreferrer>可比

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 );

更多信息:如果要定义类的自然顺序,请定义

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>

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

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