简体   繁体   English

使用特定顺序对 (Array)List 进行排序

[英]Sort an (Array)List with a specific order

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 .我有一个带有字段String color的 object 。 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):我想在颜色字段上对我的列表进行排序,以便它始终首先是白色而不是蓝色而不是黄色以及所有其他(如果可能的话 alph.ordered 但不是必需的):

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

Is there a (easy) way to do that?有没有(简单的)方法可以做到这一点?

EDIT:编辑:

I have to add a complication more...我必须添加一个并发症...
What if there can be more colors with the same name/radix?如果可以有更多同名/基数的 colors 怎么办? For ex.对于前。 whiteX, whiteY, whiteZ, blueA, blueB, ... 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...) (我无法想象如何...)

here is an other option :这是另一种选择:

Map<Integer, String> tree = new TreeMap<Integer, String>();
    List<String> listOrdre = Arrays.asList("white", "blue", "yellow", "orange", "black", "brown");
    List<String>   myList  = Arrays.asList("orange", "white", "brown", "yellow", "black");

    for (String code : myList) {
        tree.put(listOrdre.indexOf(code), code);
    }

    System.out.println(tree.values()); // -> [white, yellow, orange, black, brown]

Yes you can create a Comparator for creating your sort strategy, or define natural-order of your class implementing Comparable是的,您可以创建一个Comparator来创建排序策略,或者定义实现Comparable的类的自然顺序

As a side note :作为旁注:

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))强烈推荐,但不严格要求 (x.compareTo(y)==0) == (x.equals(y))

Example using Comparator:使用比较器的示例:

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
            }    
}

}

And in client code.并在客户端代码中。

Example:例子:

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

Read more : Collections#sort(..)阅读更多: 集合#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
        }
}

And in client code:在客户端代码中:

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

you can use comparator .你可以使用comparator

another thing you can do is set some values ( say 1 to n ) to the numbers.您可以做的另一件事是为数字设置一些值(比如 1 到 n )。 For example in your case give give white 1, give blue 2, give yellow 3. now sort those numbers.例如,在您的情况下,给白色 1,给蓝色 2,给黄色 3。现在对这些数字进行排序。

Another solution is to use enums with your comparator since enums have an index already defined ( ordinal ).另一种解决方案是将枚举与比较器一起使用,因为枚举已经定义了一个索引( ordinal )。

First, create an enum with your values in the order you want it to be sorted to.首先,按照您希望对它进行排序的顺序使用您的值创建一个枚举。

enum class MyColour {
    WHITE,
    BLUE,
    YELLOW,
    ORANGE,
    BLACK,
    BROWN
}

For each object, you can get the enum value with Mycolour.valueOf("WHITE") .对于每个对象,您可以使用Mycolour.valueOf("WHITE")获取枚举值。 Note: this is case sensitive.注意:这是区分大小写的。

Next, you can simply use your comparator.接下来,您可以简单地使用比较器。

val sortedList = list.sortedBy { it.colour } // colour being the enum value we defined.

Thanks for Réda's answer.感谢 Réda 的回答。

// Weight is the index in colorOrder, or -1 for the others
List<String> colorOrder = Arrays.asList("yellow", "blue", "white");

List<String> myList = Arrays.asList("orange", "white", "brown", "yellow", "black");

Collections.sort(myList, Comparator.comparingInt(colorOrder::indexOf).reversed());

System.out.println(myList);//[white, yellow, orange, brown, black]


And this is easy to chain some other Comparator, like alph.这很容易链接其他一些比较器,比如 alph。 order.命令。

Collections.sort(myList, Comparator.comparingInt(colorOrder::indexOf).reversed().thenComparing(Object::toString));

System.out.println(myList);//[white, yellow, black, brown, orange]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM