簡體   English   中英

使用特定順序對 (Array)List 進行排序

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

我有一個對象列表,我想按定義的順序對其進行排序。 對於前。 我有一個帶有字段String color的 object 。 我想在顏色字段上對我的列表進行排序,以便它始終首先是白色而不是藍色而不是黃色以及所有其他(如果可能的話 alph.ordered 但不是必需的):

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

有沒有(簡單的)方法可以做到這一點?

編輯:

我必須添加一個並發症...
如果可以有更多同名/基數的 colors 怎么辦? 對於前。 whiteX, whiteY, whiteZ, blueA, blueB, ...
所有的白人必須先於所有的藍人、所有的黃人和所有其他人。 仍然可以用比較器解決這個問題嗎? (我無法想象如何...)

這是另一種選擇:

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]

是的,您可以創建一個Comparator來創建排序策略,或者定義實現Comparable的類的自然順序

作為旁注:

強烈推薦,但不嚴格要求 (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 );

閱讀更多: 集合#sort(..)

如果您想定義類的自然排序,只需定義

public class MyClass implements Comparable<MyClass>{

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

在客戶端代碼中:

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

你可以使用comparator

您可以做的另一件事是為數字設置一些值(比如 1 到 n )。 例如,在您的情況下,給白色 1,給藍色 2,給黃色 3。現在對這些數字進行排序。

另一種解決方案是將枚舉與比較器一起使用,因為枚舉已經定義了一個索引( ordinal )。

首先,按照您希望對它進行排序的順序使用您的值創建一個枚舉。

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

對於每個對象,您可以使用Mycolour.valueOf("WHITE")獲取枚舉值。 注意:這是區分大小寫的。

接下來,您可以簡單地使用比較器。

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

感謝 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]


這很容易鏈接其他一些比較器,比如 alph。 命令。

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