2016-03-08 44 views
2

我試圖理清根據使用Arrays.sort()其長度的字符串數組,但這種排序字符串按字典而不是長度。這裏是我的代碼:如何排序使用Arrays.sort由長度字符串數組()

S = "No one could disentangle correctly" 
String W[] = S.split(" "); 
Arrays.sort(W); 

排序後:

correctly 
could 
disentangle 
no 
one 

,但我想要的是

no //length = 2 
one //length = 3 
could //length = 4 and likewise 
correctly 
disentangle 

我怎樣才能得到上面的輸出?請給出答案JDK 1.7 & JDK1.8。

+1

創建自己的比較。 – matt

+0

@matt所以你的意思是我不能通過Arrays.sort() –

+1

來實現這一點。我的意思是使用Arrays.sort(Object [],Comparator)的2參數版本。 – matt

回答

4

或稍微簡單一些。如果你正在使用JDK 1.8上面,那麼你可以使用lambda表達式亞光答案。但是,如果你正在使用JDK 1.7或更早版本嘗試寫一個自定義比較這樣的:

String S = "No one could disentangle correctly"; 
String W[] = S.split(" "); 
Arrays.sort(W, new java.util.Comparator<String>() { 
    @Override 
    public int compare(String s1, String s2) { 
     // TODO: Argument validation (nullity, length) 
     return s1.length() - s2.length();// comparision 
    } 
}); 
18
Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length())); 
+0

感謝您的幫助。 –

10

替代,比亞光的版本

Arrays.sort(W, Comparator.comparingInt(String::length)); 
+2

這也可以使用更完整的比較器打開。 'Comparator.comparingInt(String :: length).thenComparing(Comparator.naturalOrder());' – matt

+0

如何以降序得到它? –

0
import java.util.*; 

class SortStringArray 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     String S = "No one could disentangle correctly"; 
     String W[] = S.split(" "); 
     Arrays.sort(W, new StringLengthComparator()); 
     for(String str: W) 
     System.out.println(str); //print Your Expected Result. 
    } 
} 
class StringLengthComparator implements Comparator<String>{ //Custom Comparator class according to your need 

    @Override 
     public int compare(String str1, String str2) { 
      return str1.length() - str2.length();// compare length of Strings 
     } 
}