我有一个这样的对象
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 条记录,按创建日期排序,并将结果也以列表形式返回。
结果列表 = 关键字列表 = [{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())
最佳答案
我猜你可以分两步完成(假设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
一步完成,但不确定它的可读性如何。
关于java-8 - java 8 中的限制和获取平面列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50489569/