public class Result {
...
private Integer averageRating;
}
I have a list of result List<Result>
. I want to sort them by averageRating
and then want to get form a specific index to a specific index like 10 to 20.
I can do that using Collection.sort()
using Comparator.comparing()
then take sublist from list. But problem is higher index may be greater than the list size, that's why I have to manually handle that. Like 10 to 20 but list size is 15 then 5 items will be output.
But how can I do that using Java Stream API ?
I tried something but not worked:
List<Result> result = list.stream().sorted(e -> e.getAverageRating()).collect(Collectors.toList());
.sorted(e -> e.getAverageRating())
you should use.sorted(Comparator.comparing(e -> e.getAverageRating()))
. and not sure why you couldn't take asubList
after stream operation when you already knew how to do that.But problem is higher index may be greater than the list size, that's why I have to manually handle that.
new partfilter
ing elements from the list instream
pipeline, you can perform.subList(startIndex, higherIndex > list.size() ? list.size() : higherIndex)