【发布时间】:2020-06-30 20:36:33
【问题描述】:
public class Result {
...
private Integer averageRating;
}
我有一个结果列表List<Result>。我想按averageRating 对它们进行排序,然后想从特定索引中获取特定索引,例如 10 到 20。
我可以使用Collection.sort() 使用Comparator.comparing() 来做到这一点,然后从列表中获取子列表。但问题是更高的索引可能大于列表大小,这就是我必须手动处理的原因。像 10 到 20,但列表大小为 15,则将输出 5 个项目。
但是如何使用 Java Stream API 做到这一点?
我尝试了一些但没有成功:
List<Result> result = list.stream().sorted(e -> e.getAverageRating()).collect(Collectors.toList());
【问题讨论】:
-
您应该使用
.sorted(Comparator.comparing(e -> e.getAverageRating()))而不是.sorted(e -> e.getAverageRating())。并且不知道为什么在您已经知道如何进行流操作后不能使用subList。 -
@Naman 我更新了问题
But problem is higher index may be greater than the list size, that's why I have to manually handle that.新部分 -
如果值可能高于列表大小并且您不是
filtering 来自stream管道中列表的元素,您可以执行.subList(startIndex, higherIndex > list.size() ? list.size() : higherIndex)
标签: java java-8 java-stream