Java 8流过滤器 - 基于排序的pdate

Bha*_*a S 2 java sorting java-8 java-stream

我试图在过滤器中对字段进行排序.

输入文件/样本记录:

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
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

在这里,我需要根据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);
Run Code Online (Sandbox Code Playgroud)

不知道如何排序

"order by pdate DESC"
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Grz*_*rek 8

您可以使用.sorted()Stream API方法:

.sorted(Comparator.comparing(Document::getPDate).reversed())
Run Code Online (Sandbox Code Playgroud)

完整的,重构的例子:

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))
Run Code Online (Sandbox Code Playgroud)

几件事要记住:

  • 如果您不关心List实现,请使用 Collectors.toList()
  • collect()是一个终端操作,应该作为最后一个操作调用
  • .parallel().sequential()这完全是无用的 - 如果你想并行化,坚持.parallel()如果不坚持,不要写任何东西,默认情况下流是顺序的
  • 为了排序,整个Stream将被加载到内存中

  • @ M.Prokhorov好主意 - 为了以防万一,我添加了相关信息 - 但我认为OP意识到只能在满载数据集上执行排序 (2认同)