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

时间:2016-08-03 12:05:45

标签: scala collections

我有一个List,它具有Scala中的属性(StarRating,Price),如下所示:

ListBuffer(RatingAndPriceDataset(3.5,200), RatingAndPriceDataset(4.5,500),RatingAndPriceDataset(3.5,100), RatingAndPriceDataset(3.0,100))

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

RatingAndPriceDataset(4.5,500),RatingAndPriceDataset(3.5,100), RatingAndPriceDataset(3.5,200)

可以看出,星级评级是排序中更高优先级的评级。我尝试了一些东西,但未能做到这一点。如果我根据星级评级然后按价格排序,则无法保持优先级顺序。

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

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

1 个答案:

答案 0 :(得分:4)

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

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))
相关问题