java-8 - 在 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())
解决方案
好吧,我猜你可以分两步完成(假设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
,但不确定它的可读性如何。
推荐阅读
- python - 使用 PyMC3 线性拟合的后验分布,预测给定 X 的 y 的置信区间
- javascript - 当父组件和子组件也是功能组件时,如何将函数作为道具传递?
- postgresql - 如何在 Postgresql 中查找带有任何预定义标签的帖子
- unit-testing - TDD + DDD:模型抽象
- python - 如何使用 url_for 将 jinja 变量传递到烧瓶中
- python - 在python中将数据框绘制为pdf中的表格
- c - 获得任意两个数组的最大总起点(两个数组中的最大和路径)
- javascript - 是否有一个包装器可以在不使用 try-catch 块的情况下编写异步等待函数
- visual-studio-code - 如何在 Visual Studio 代码的 Markdown 中禁用乳胶数学片段的拼写检查?
- nim-lang - Nim 语言是否具有较短的对象初始化符号?