【发布时间】:2021-04-02 05:07:03
【问题描述】:
我必须在字段issueDate(输入String)上过滤List<Card>,其中卡片要显示到最近7年的日期。
我尝试过的解决方案是将issueDate字段从String解析为Date,然后应用date.after(startDate)和date.before(endDate)如下:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cardList.stream()
.map(s->s.getIssueDate())
.filter(dt -> sdf.parse(dt).after(sdf.parse("2020-06-08")) &&
sdf.parse(dt).before(sdf.parse("2020-08-12")))
.collect(Collectors.toList());
甚至不能申请循环,因为可以发行数百张卡,它会通过迭代每个发卡日期(字符串到日期和检查年份)来影响性能
谁能提出一个解决这个问题的好方法?
【问题讨论】:
-
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDate。 -
迭代几百张卡片并不需要很长时间。无论是使用
for循环还是其他方式。
标签: arraylist java-8 java-stream simpledateformat java-time