Bugs Happen :
I have an array like this:
"Turkish 1"
"Indonesian 1"
"Malay 2"
"Indonesian 3"
"Yiddish 1"
"Urdu 2"
"Malay 1"
"Indonesian 2"
"Urdu 1"
And I want to sort it like this:
"Urdu 1"
"Urdu 2"
"Indonesian 1"
"Indonesian 2"
"Indonesian 3"
"Malay 1"
"Malay 2"
"Turkish 1"
"Yiddish 1"
Note that items starting from "U" are at the top and the rest of them are alphabetically sorted. How can I achieve this using some sorting algo in Java or Kotlin?
Right now, I only know to loop over the list and put items starting from U to top of the list.
Also, if it possible even in Sqlite, please share that too.
Thanks.
Andreas :
Best way to apply a high-level sort override, is to derive an integer value from the override condition, then sort by that first.
In Java:
String[] strings = {
"Turkish 1",
"Indonesian 1",
"Malay 2",
"Indonesian 3",
"Yiddish 1",
"Urdu 2",
"Malay 1",
"Indonesian 2",
"Urdu 1" };
Arrays.sort(strings, Comparator.comparingInt((String s) -> s.startsWith("U") ? 0 : 1)
.thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(strings));
Output
[Urdu 1, Urdu 2, Indonesian 1, Indonesian 2, Indonesian 3, Malay 1, Malay 2, Turkish 1, Yiddish 1]
In SQL:
SELECT description
FROM mytable
ORDER BY CASE WHEN description LIKE 'U%' THEN 0 ELSE 1 END
, description
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=366773&siteId=1