我有3个值,如
a^100,b^200,c^150
我需要按照
的顺序对这些值进行排序b^200,c^150,a^100
我怎么能在java中做到这一点?
答案 0 :(得分:3)
使用自定义Comparator
,如下所示:
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);
}
}
你可以像这样使用它:
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);
}
答案 1 :(得分:0)
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]);