How to manipulate an array similar to an ORDER BY clause in SQL?
-
21-09-2019 - |
Question
My data has been placed into an array, but unfortunately not in the order I want it in...
String[][] databaseToArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"John", "Nick", "likes", "2", "yes" },
{"Drew", "MTV", "dislikes", "4", "no" },
{"Fred", "CNN", "okay", "3", "no" },
{"Beth", "Fox", "valid", "1", "yes" }
};
How do I manipulate this array so that when I loop through it the order is by the amount , similar to SELECT * FROM "databaseToArray" ORDER BY "Amount"
aka
String[][] reorganizedArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"Beth", "Fox", "valid", "1", "yes" },
{"John", "Nick", "likes", "2", "yes" },
{"Fred", "CNN", "okay", "3", "no" },
{"Drew", "MTV", "dislikes", "4", "no" }
};
Solution
You'll want to pass a Comparator to the Arrays.sort method. I haven't done Java in 5 years, but it should be easily doable. Maybe someone can clean up this example I'm about to write, since I'm pretty certain I'll get something wrong.
String[][] databaseToArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"John", "Nick", "likes", "2", "yes" },
{"Drew", "MTV", "dislikes", "4", "no" },
{"Fred", "CNN", "okay", "3", "no" },
{"Beth", "Fox", "valid", "1", "yes" }
};
Arrays.sort(databaseToArray, new Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[3].compareTo(b[3]);
}
});
OTHER TIPS
I found the sort method on the processing website, but this is only for One-Dimensional Arrays...
http://processing.org/reference/sort_.html
float[] a = { 3, 5, 2, 4, 1 };
a = sort(a);
println(a);
// Prints 1, 2, 3, 4, 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow