javasortingcollectionsguava

How to sort collection in my pre-defined order?


For example, I have next list of strings:

List<String> s = newArrayList("string", "someString", "anotherStr", "yetAnotherString", "Something");

I need to sort it in a special way, for example: yetAnotherString, someString, anotherStr, string, Something

so there is no alphabetical or lexicographical ordering, in pseudo code it would like:

if (el == yetAnotherString)
{
 set order 1;
}
else if (someString)
{
 set order 2;
} ....

Do java Collections or guava allows doing such ordering?


Solution

  • If such an ordering exists, then you should be able express it in a Comparator, ie: given two elements decide their order. And once you do so, you can pass your Comparator to the Collections.sort method.

    Collections.sort(list,comparator);