2011-03-23 2 views
2

私はJavaでこれを行うことができますどのようにjavaを使用して英数字値に基づいてソートする方法は?

b^200,c^150,a^100 

のためにこれらの値をソートする必要が

a^100,b^200,c^150 

のような3つの値を持つんですか?

+0

私は値がに意図されているかを理解していませんソートされる。ソートルールを説明できますか? – sleske

+0

Javaを使用してソートを実行する方法や、 "a^100"と "b^200"を正しく比較するアルゴリズムを実行する方法を尋ねていますか? – RonK

+0

^100,200,150.comのように値を取得し、並べ替えて結果を200,150,100とした後に整数を取得します。 – Marshal

答えて

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..Itはうまく動作します.. – Marshal

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]); 
関連する問題