Sort an (Array)List with a specific order

Viewed 13638

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?

EDIT:

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

5 Answers

Another solution is to use enums with your comparator since enums have an index already defined ( 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"). 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.

// 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. order.

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

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