2017-06-20 70 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'日期吗? –

相关问题