2017-06-20 71 views
-1

這是This的確切副本,但有一個棘手的區別。 我有一個'LOBServiceRequestDetails'類型的ArrayList,它使用來自web服務的值進行更新。一些LOBServiceRequestDetails的varriables的是如下,如何根據字符串格式的日期對ArrayList進行排序?

  • 字符串#AGENTID
  • 字符串#creationDate(DD/MM/YYYY HH:MM:SS格式)

我想進行排序,根據該列表到creationDate。我有一種方法是在LOBServiceRequestDetails模型類中實現Comparable並重寫compareTo方法,但由於某些問題,我無法更改此類。所以我使用Collection.sort如下,

 DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); 
    Collections.sort(lOBServiceRequestDetailsList, new Comparator<LOBServiceRequestDetails>() { 
      public int compare(LOBServiceRequestDetails o1, LOBServiceRequestDetails o2) { 
       if (o1.getCreationDate() == null || o2.getCreationDate() == null) 
        return 0; 
       try{ 
        return sdf.parse(o1.getCreationDate()).compareTo(sdf.parse(o2.getCreationDate())); 
       } catch (ParseException e) { 
        throw new IllegalArgumentException(e); 
       } 
      } 
     }); 

但是,這不按預期工作。任何幫助表示讚賞。

預期輸出:

[LOBServiceRequestDetails [creationDate = 22/05/2017 10點31分二十○秒,的agentId = AG11],LOBServiceRequestDetails [creationDate = 7月2日/ 2017 11點10分20秒 ,agentId = ag12],LOBServiceRequestDetails [creationDate = 06/12/2016 12:51:20,agentId = ag13],LOBServiceRequestDetails [creationDate = 17/12/2015 06:44:20,agentId = ag14]]

實際產量:

[LOBServiceRequestDetails [creationDate = 06/12/2016年十一時10分20秒,的agentId = AG11],LOBServiceRequestDetails [creationDate = 17/12 /到2015年6點44分20秒,的agentId = AG12],LOBServiceRequestDetails [ creationDate = 7月2日/ 2017 11時十分20秒,的agentId = AG13],LOBServiceRequestDetails [creationDate = 22/05/2017 10點31分二十秒,的agentId = AG14]]

+0

究竟是不是工作? –

+1

您在compareTo –

+0

@DavisMolinari編輯代碼的兩側使用o1.getCreationDate(),但仍未得到排序列表 –

回答

1

您使用在compareTo兩側的o1.getCreationDate():

return sdf.parse(o1.getCreationDate()).compareTo(sdf.parse(o1.getCreationDate())); 

編輯:這是一個固定的問題,但它仍然是一個空值處理方式的錯誤,因爲正如「OH GOD SPIDERS」的評論中所解釋的,如果兩個日期中的一個爲空,那麼它們被認爲是相等的。 比如你改變你的條件是這樣的:

   if (o1.getCreationDate() == null) return 1; 
       if (o2.getCreationDate() == null) return -1; 
      try{... 

你在列表的末尾放空值。

截圖輸出的符合預期的結果 enter image description here

+0

編輯的代碼,但仍然沒有得到排序列表。 –

+0

@VikasYadav我嘗試了正確的代碼(使用o2),並且它按預期工作 –

+0

@DavisMolinari在測試數據中包含了一些'null'日期嗎? –

相關問題