【问题标题】:Sort Ascending and Descending in a List在列表中升序和降序排序
【发布时间】:2016-08-03 12:05:44
【问题描述】:

我有一个列表,它在 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

【问题讨论】:

  • 当您选择三个最低价格时,您是如何包含PriceDataset(4.5, 500) 的?我错过了什么吗?
  • @911DidBush 我没有进行嵌套或优先排序。因此,如果我先按星级排序,然后按价格排序,我不会得到预期的结果。有帮助吗?
  • @ganesshkumar:我改进了描述。所以我的排序优先顺序是星级,然后是价格。希望有帮助

标签: scala collections


【解决方案1】:

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

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))

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 2016-10-18
    • 2011-08-25
    • 2015-03-09
    • 1970-01-01
    • 2018-01-14
    • 2020-02-08
    • 2020-10-05
    相关资源
    最近更新 更多