i have a string array consisting of a name and a score. I want to sort that array by score. Problem is, considering it's a string array, the scores are strings which results in 13,16,2,5,6 and not 2,5,6,13,16. I am using this code:
int spaceIndex;
String[][] scoreboard;
String[] playername;
String[] score;
int sbsize;
array1.add("Thomas" + ":" + 5);
array1.add("Blueb" + ":" + 6);
array1.add("James" + ":" + 16);
array1.add("Hleb" + ":" + 13);
array1.add("Sabbat" + ":" + 2);
sbsize = array1.size();
scoreboard = new String[sbsize][2];
playername = new String[sbsize];
score = new String[sbsize];
pos2 = new int[sbsize];
for (int i=0; i<array1.size(); i++)
{
spaceIndex = array1.get(i).indexOf(':');
scoreboard[i][0] = array1.get(i).substring(0, spaceIndex);
scoreboard[i][1] = array1.get(i).substring(spaceIndex+1, array1.get(i).length());
}
Arrays.sort(scoreboard, new Comparator<String[]>() {
@Override
public int compare(String[] entry1, String[] entry2) {
String time1 = entry1[1];
String time2 = entry2[1];
return time1.compareTo(time2);
}
});
What is the solution?
get(i). length()); } Arrays. sort(scoreboard, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { String time1 = entry1[1]; String time2 = entry2[1]; return time1. compareTo(time2); } });
Just like numeric arrays, you can also sort string array using the sort function. When you pass the string array, the array is sorted in ascending alphabetical order. To sort the array in descending alphabetical order, you should provide the Collections interface method reverseOrder () as the second argument.
What is an Array? An array is a common data structure used to store an ordered list of items. The array elements are typed. For example, you could create an array of characters to represent the vowels in the alphabet: 1.
This is the easy way of Sorting String Array:
Arrays.sort(mystringarray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With