Bhaskar Mishra Bhaskar Mishra - 1 year ago 130
Scala Question

Sort Ascending and Descending in a List

I have a List which has attributes (StarRating, Price) like the below in Scala:

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

My Sort Priority Order is :
First Sort on the basis of Star rating (descending) and then pick three lowest prices. So in the above example , I get the list as :

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

as can be seen the star rating is the one which comes as higher Priority in sort. I tried a few things but failed to do the sort. If i sort on the basis of a star rating then Price, it fails to keep the priority order.

What I get from a calling a method is a list like this (as above). The list will have some data like below (example):

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

Answer Source

Using the data in the table you've provided (which is different than the data in your code):

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