在列表中按升序和降序排序

Bha*_*hra 1 collections scala

我有一个列表,它在 Scala 中具有如下属性(星级、价格):

ListBuffer(RatingAndPriceDataset(3.5,200), RatingAndPriceDataset(4.5,500),RatingAndPriceDataset(3.5,100), RatingAndPriceDataset(3.0,100))
Run Code Online (Sandbox Code Playgroud)

我的排序优先顺序是:首先根据星级(降序)排序,然后选择三个最低价格。所以在上面的例子中,我得到的列表如下:

RatingAndPriceDataset(4.5,500),RatingAndPriceDataset(3.5,100), RatingAndPriceDataset(3.5,200)
Run Code Online (Sandbox Code Playgroud)

可以看出,星级是排序中具有更高优先级的星级。我尝试了几件事,但未能做到这一点。如果我根据星级然后价格进行排序,则无法保持优先顺序。

我从调用方法中得到的是这样的列表(如上)。该列表将包含一些如下所示的数据(示例):

StarRating Price
3.5         200
4.5         100
4.5         1000
5.0         900
3.0         1000
3.0         100


**Expected result:**

StarRating Price
5.0         900
4.5         100
4.5         1000
Run Code Online (Sandbox Code Playgroud)

Paw*_*nko 6

使用您提供的表中的数据(与代码中的数据不同):

val input = ListBuffer(RatingAndPriceDataset(3.5,200), RatingAndPriceDataset(4.5,100),RatingAndPriceDataset(4.5,1000), RatingAndPriceDataset(5.0, 900), RatingAndPriceDataset(3.0, 1000), RatingAndPriceDataset(3.0, 100))
val output = input.sortBy(x => (-x.StarRating, x.Price)).take(3) // By using `-` in front of `x.StarRating` we're getting descending order of sorting

println(output) // ListBuffer(RatingAndPriceDataset(5.0,900), RatingAndPriceDataset(4.5,100), RatingAndPriceDataset(4.5,1000))
Run Code Online (Sandbox Code Playgroud)