Java 8流过滤器 - 基于排序的pdate [英] Java 8 Stream Filter - Sort based pdate

查看:269
本文介绍了Java 8流过滤器 - 基于排序的pdate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Am trying to sort the filed in filter.

输入文档/样本记录:

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进行排序。

Here, I need to sort based on 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方法:

You can use .sorted() Stream API method:

.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))






很少有事情需要记住:


Few things to remember about:


  • 如果您不关心 List 实现,请使用
    Collectors.toList()

  • collect()是一个终端操作,应作为最后一个操作调用

  • .parallel()。顺序()这完全没用 - 如果你想要并行化
    ,坚持 .parallel()如果没有,请不要写
    任何内容,默认情况下流是顺序的

  • 整个Stream将被加载到内存中以便排序

  • If you do not care about the List implementation, use Collectors.toList()
  • The collect() is a terminal operation and should be called as the last operation
  • .parallel().sequential() this is totally useless - if you want to parallelize, stick to .parallel() if not, do not write anything, streams are sequential by default
  • The whole Stream will be loaded to the memory for the sake of sorting

这篇关于Java 8流过滤器 - 基于排序的pdate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆