簡體   English   中英

Java 排序列表,然后使用 Stream api 從列表中獲取子列表

[英]Java sort list and then take sublist from list using Stream api

public class Result {
  ...
  private Integer averageRating;
}

我有一個結果List<Result> 我想通過averageRating對它們進行排序,然后希望從特定索引到特定索引,如 10 到 20。

我可以使用Collection.sort()使用Comparator.comparing()來做到這一點,然后從列表中獲取子列表。 但問題是更高的索引可能大於列表大小,這就是我必須手動處理的原因。 像 10 到 20,但列表大小為 15,那么 5 項將是 output。

但是我怎么能用 Java Stream API 做到這一點?

我嘗試了一些但沒有奏效:

List<Result> result = list.stream().sorted(e -> e.getAverageRating()).collect(Collectors.toList());

嘗試以下操作:

int from = 10;
int to = 20;

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

它應該跳過排序后的 stream 的前 10 個元素,然后取不超過指定范圍的差。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM