Originally Posted by
Purple01
...So arrayList is full of these string1 things.
Now start and end are both number.
Is there a way that i can sort the arrayList on the start?
Like that I want 1-4 before 3-2?
One way would be to create a custom comparator and use Collections.sort. It could go like this:
class CustomComparator implements Comparator<String>
{
@Override
public int compare(String str1, String str2)
{
//Code that extracts the integer values of substrings of str1 and str2
// Call them int1 and int2
// Return int1-int2
}
Then, call the Collections.sort function with your ArrayList<String> object like this:
ArrayList<String> al = new ArrayList();
//
// Code to populate al goes here
//
System.out.println("Original: ");
for (String str : al) {
System.out.println(" " + str);
}
// For amusement, just sort by comparing strings
Collections.sort(al);
System.out.println("Natural sort of the Strings: ");
for (String str : al) {
System.out.println(" " + str);
}
// The real goal: Sort by numeric value of the first item in the "num1-num2" Strings
Collections.sort(al, new CustomComparator());
System.out.println("CustomComparator sort of the Strings: ");
for (String str : al) {
System.out.println(" " + str);
}
Example output
Original:
1-10
21-18
25-4
25-12
1-9
17-12
10-16
2-4
17-13
2-15
Natural sort of the Strings:
1-10
1-9
10-16
17-12
17-13
2-15
2-4
21-18
25-12
25-4
CustomComparator sort of the Strings:
1-10
1-9
2-15
2-4
10-16
17-12
17-13
21-18
25-12
25-4
Cheers!
Z