2011-09-27 199 views
16

我想按長度排序字符串的ArrayList,但不是按數字順序排列。按長度排序字符串的ArrayList

比方說,列表中包含這些詞:

cucumber 
aeronomical 
bacon 
tea 
telescopic 
fantasmagorical 

他們需要通過其長度差責令其特殊的字符串,例如:

intelligent 

所以最終名單看起來像這樣(括號內的區別):

aeronomical  (0) 
telescopic  (1) 
fantasmagorical (3) - give priority to positive differences? doesn't really matter 
cucumber  (3) 
bacon   (6) 
tea    (8) 

回答

27

使用自定義比較器:

public class MyComparator implements java.util.Comparator<String> { 

    private int referenceLength; 

    public MyComparator(String reference) { 
     super(); 
     this.referenceLength = reference.length(); 
    } 

    public int compare(String s1, String s2) { 
     int dist1 = Math.abs(s1.length() - referenceLength); 
     int dist2 = Math.abs(s2.length() - referenceLength); 

     return dist1 - dist2; 
    } 
} 

然後使用java.util.Collections.sort(List, Comparator)對列表進行排序。

+0

積極差異的優先順序可以通過積極的差異乘以兩個,負的差異兩個負數,然後加一。 –

+0

您應該參考長度最後。 –

4

你會這樣做的Collections.sort()版本,需要明確Comparator

+0

@downvoter - 你更喜歡我提出答案,而不是教導OP在哪裏找到信息? – parsifal

+7

Downvoted,因爲...癢癢downvote手指?它應該是一個評論?司法部門的敵人? –

+2

由於以上評論而被Downvoted:D – user1613360

5
This will help you - String in Ascending order 


class StringLengthListSort implements Comparator<String>{ 

    @Override 
    public int compare(String s1, String s2) { 
    return s1.length() - s2.length(); 
    } 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
    List<String> list = new ArrayList<String>(); 
    StringLengthListSort ss = new StringLengthListSort(); 
    list.add("ram"); 
    list.add("rahim"); 
    list.add("ramshyam"); 
    Collections.sort(list, ss); 
    System.out.println(list); 
    } 

} 
5

如果您使用的是Java 8+你可以使用lambda表達式實現(@副把的答案)比較

List<String> strings = Arrays.asList(new String[] {"cucumber","aeronomical","bacon","tea","telescopic","fantasmagorical"}); 
strings.sort((s1, s2) -> Math.abs(s1.length() - "intelligent".length()) - Math.abs(s2.length() - "intelligent".length())); 
+1

Java 8+的最佳解決方案。簡短而精確。 –

-1

我想提出的解決方案是非法的。

比較器接口契約要求比較方法與equals方法一致。

這意味着如果你有x.compareTo(y) == 0那麼你必須有x.equals(y) == true

因此,也許這些解決方案在實踐中有效,但他們不能保證,並可能在下一個版本中破解。

+1

如果是這樣的話,你不能*任何*自定義字符串比較器。 – Clashsoft