2011-05-21 115 views
4

我在一個包含許多有用的比較器實現的foss庫之後,它有很多小無聊的比較器,可以去。有誰知道Java比較器庫?

阿帕奇公地比較

  • 反向
  • 空第一/ null的最後
  • 自然
  • 變壓器

有一些的arent許多其他有用的可重複使用的可能性可用。

  • 空白忽略
  • 空白正火
  • 數意識到字符串 - 如 「蘋果10」> 「蘋果2」。

@SPF 伊夫包括一些僞代碼演示如何能夠正常化,並不會產生任何臨時字符串等一通比較雖然這是未經測試,可能不工作它wouldnt花費太多有一個工作比較快。

while { 

    while 
     get next char from $string1 
     if none left then 
      $string1 > $string2 return +1; 
     get next char from $string1 
     increase $index1 
     if previous was whitespace and this is whitespace then 
      continue; 
     end if 
    end while 

    while 
    get next char from $string2 
    if none left then 
     $string2 > $string1 return +1; 
    get next char from $string2 
    increase $index2 
    if previous was whitespace and this is whitespace then 
     continue; 
    end if 
    end while 

    result = $char1 - $char2 
    if result != 0 return 
} 

回答

5

我不認爲你會得到許多現成的比較,但GuavaOrdering類都擴展了比較功能,並增加了一些有用的默認實現爲工廠方法

而且也:兩個GuavaApache Commons/Lang(我說過)將幫助您分別使用CompareToBuilderComparisonChain來實現自定義比較器或可比較結果。恐怕沒有比這更好的了。


而有關這些要求:

有一些的arent這麼多的其他有用的可重複使用的可能性。

  • 空白忽略
  • 空白正火
  • 數意識到字符串 - 如 「蘋果10」> 「蘋果2」。

這不是聰明做任何的這一個比較,因爲這意味着你的未修改數據仍然在收集和Comparator需要進行必要的轉換兩次,每次比較。現在想想用幾百萬個條目對一個Array進行排序。需要多少次字符串轉換?

首先對數據進行規範化然後對其進行排序總是比較明智​​的。

+0

不完全 - 如果這是真的,那麼將不需要比較器,您將構建可比公司的列表。 – 2011-05-22 08:17:52

+0

作爲一個例子,如果在diff util中使用comaprator,有時候您想要忽略空白,其他時候您不需要。切換比較器比清理整個「來源」更容易。 – 2011-05-22 08:18:48

+0

@mP更容易,是的。但是效率低下很多 – 2011-05-23 04:33:53

1

從3.0.2開始的Commons Lang將在org.apache.commons.lang3.compare包中包含Collections比較器的副本。隨意提出更多建議。