首页 > 解决方案 > 在 java 8 中限制和获取平面列表

问题描述

我有一个这样的对象

public class Keyword
{
  private int id;
  private DateTime creationDate
  private int subjectId
  ...
}

所以现在我有如下数据列表

关键字列表= [{1,'2018-10-20',10},{1,'2018-10-21',10},{1,'2018-10-22',10},{1,'2018 -10-23',20},{1,'2018-10-24',20}{1,'2018-10-25',20},{1,'2018-10-26',30}, {1,'2018-10-27',30},{1,'2018-10-28',40}]

我想限制此列表的主题 ID

例如:如果我提供的限制为 2,则它应该只包含每个主题 ID 的最新 2 条记录,按 creationDate 排序,并将结果也作为列表返回。

resultList = KeywordList = [{1,'2018-10-21',10},{1,'2018-10-22',10},{1,'2018-10-24',20},{1, '2018-10-25',20},{1,'2018-10-26',30},{1,'2018-10-27',30},{1,'2018-10-28', 40}]

我们如何在 Java 8 中实现这种事情我已经以这种方式实现了它。但我对这个代码性能有疑问。

dataList.stream()
        .collect(Collectors.groupingBy(Keyword::getSubjectId,
            Collectors.collectingAndThen(Collectors.toList(),
                myList-> myList.stream().sorted(Comparator.comparing(Keyword::getCreationDate).reversed()).limit(limit)
                    .collect(Collectors.toList()))))
        .values().stream().flatMap(List::stream).collect(Collectors.toList())

标签: java-8

解决方案


好吧,我猜你可以分两步完成(假设DateTime是可比的):

    yourInitialList
            .stream()
            .collect(Collectors.groupingBy(Keyword::getSubjectId));

    List<Keyword> result = map.values()
            .stream()
            .flatMap(x -> x.stream()
                          .sorted(Comparator.comparing(Keyword::getCreationDate))
                          .limit(2))
            .collect(Collectors.toList());

我猜这也可以一步完成Collectors.collectingAndThen,但不确定它的可读性如何。


推荐阅读