Reputation: 261
I'm having 3 values like
a^100,b^200,c^150
I need to sort these values in the order of
b^200,c^150,a^100
How can i do this in java?
Upvotes: 2
Views: 4968
Reputation: 12575
String sample = "a^100,b^200,c^150";
List data = Arrays.asList(sample.split(","));
Collections.sort(data, Collections.reverseOrder( new Comparator<String>() {
public int compare (String obj1,String obj2)
{
String num1 = obj1.split("\\^")[1];
String num2 = obj2.split("\\^")[1];
return num1.compareTo(num2);
}
}));
String sortedSample[]= (String[])data.toArray(new String[data.size()]);
for (int z=0; z< sortedSample.length;z++ )
System.out.println(sortedSample[z]);
Upvotes: 0
Reputation: 54806
Use a custom Comparator
, like this one:
public class IntegerSubstringCompare implements Comparator<String> {
@Override
public int compare(String left, String right) {
Integer leftInt = Integer.parseInt(left.substring(left.indexOf("^") + 1));
Integer rightInt = Integer.parseInt(right.substring(right.indexOf("^") + 1));
return -1 * leftInt.compareTo(rightInt);
}
}
You can use it like this:
public static void main(String[] args) {
String[] input = {"a^100", "b^200", "c^150"};
List<String> inputList = Arrays.asList(input);
Collections.sort(inputList, new IntegerSubstringCompare());
System.out.println(inputList);
}
Upvotes: 3