2011-03-23 202 views
2

我有3個值一樣如何使用java基於字母數字值進行排序?

a^100,b^200,c^150 

我需要這些值的

b^200,c^150,a^100 

順序我怎樣才能在Java中做這樣?

+0

從你的例子,我不明白這些值的意思排序。你能描述一下排序規則嗎? – sleske 2011-03-23 09:51:33

+0

您是在問如何使用Java或用於比較「a^100」和「b^200」的算法進行排序? – RonK 2011-03-23 09:52:53

+0

在^ like 100,200,150.com之後得到整數,然後對結果進行排序並給出200,150,100。 – Marshal 2011-03-23 09:54:54

回答

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); 
} 
+0

謝謝aroth..Its工作正常.. – Marshal 2011-03-23 10:09:18

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]); 
相關問題