在java 8中限制并获得平面列表

Pra*_*ath 2 java-8

我有一个像这样的对象

public class Keyword
{
  private int id;
  private DateTime creationDate
  private int subjectId
  ...
}
Run Code Online (Sandbox Code Playgroud)

所以现在我有像下面这样的数据列表

KeywordList = [{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())
Run Code Online (Sandbox Code Playgroud)

Eug*_*ene 5

那么你可以分两步完成它(假设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());
Run Code Online (Sandbox Code Playgroud)

Collectors.collectingAndThen我猜这一步也是可行的,但不确定它的可读性.

  • @Prabhath你在这问我?对不起,我不理解你,是的,如果需要,你可以简单地在比较器中添加`reversed` (2认同)