我正在尝试对过滤器中的文件进行排序。
输入文档/示例记录:
DocumentList: [
Document{
{
_id=5975ff00a213745b5e1a8ed9,
u_id=,
mailboxcontent_id=5975ff00a213745b5e1a8ed8,
idmapping=Document{
{ptype=PDF, cid=00988, normalizedcid=00988, systeminstanceid=, sourceschemaname=, pid=0244810006}
},
batchid=null,
pdate=Tue Jul 11 17:52:25 IST 2017, locale=en_US
}
},
Document{
{
_id=597608aba213742554f537a6,
u_id=,
mailboxcontent_id=597608aba213742554f537a3,
idmapping=Document{
{platformtype=PDF, cid=00999, normalizedcid=00999, systeminstanceid=, sourceschemaname=, pid=0244810006}
},
batchid=null,
pdate=Fri Jul 28 01:26:22 IST 2017,
locale=en_US
}
}
]
这里,我需要根据pdate进行排序。
List<Document> outList = documentList.stream()
.filter(p -> p.getInteger(CommonConstants.VISIBILITY) == 1)
.parallel()
.sequential()
.collect(Collectors.toCollection(ArrayList::new))
.sort()
.skip(skipValue)
.limit(limtValue);
不确定如何排序
"order by pdate DESC"
提前致谢!
最佳答案
您可以使用 .sorted()
流 API 方法:
.sorted(Comparator.comparing(Document::getPDate).reversed())
以及完整的重构示例:
List<Document> outList = documentList.stream()
.filter(p -> p.getInteger(CommonConstants.VISIBILITY) == 1)
.sorted(Comparator.comparing(Document::getPDate).reversed())
.skip(skipValue).limit(limtValue)
.collect(Collectors.toCollection(ArrayList::new))
一些需要记住的事情:
- 如果您不关心
List
的实现,请使用Collectors.toList()
collect()
是终端操作,应作为最后一个操作调用.parallel().sequential()
这完全没用 - 如果你 想要并行化,坚持使用.parallel()
如果不是,不要写 任何东西,流默认是顺序的- 为了排序,整个Stream会被加载到内存
关于Java 8 Stream Filter - 基于排序的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45421453/