【问题标题】:Java sort list and then take sublist from list using Stream apiJava排序列表,然后使用Stream api从列表中获取子列表
【发布时间】: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 -&gt; e.getAverageRating())) 而不是.sorted(e -&gt; 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 &gt; list.size() ? list.size() : higherIndex)

标签: java java-8 java-stream


【解决方案1】:

尝试以下方法:

int from = 10;
int to = 20;

List<Result> result = list.stream()
    .sorted(Comparator.comparing(Result::getAverageRating))
    .skip(from)
    .limit(to - from)
    .collect(Collectors.toList());

它应该跳过排序流的前 10 个元素,然后取不超过指定范围的差。

【讨论】:

  • .limit(higherIndex-lowerIndex)
猜你喜欢
  • 1970-01-01
  • 2017-09-26
  • 2021-06-28
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
相关资源
最近更新 更多