Gambit1614
Gambit1614

Reputation: 8811

Sort list of string based on length

I have a list of strings

List("cbda","xyz","jlki","badce")

I want to sort the strings in such a way that the odd length strings are sorted in descending order and even length strings are sorted in ascending order

List("abcd","zyx","ijkl","edcba")

Now I have implemented this by iterating over each elements separately, then finding their length and sorting them accordingly. Finally I store them in separate list. I was hoping to know if there is any other efficient way to do this in Scala, or any shorter way to do this (like some sort of list comprehensions we have in Python) ?

Upvotes: 0

Views: 1159

Answers (2)

cvargascr
cvargascr

Reputation: 113

You can do it with sortWith and map:

list.map(s => {if(s.length % 2 == 0) s.sortWith(_ < _) else s.sortWith(_ > _)})

Upvotes: 3

Frederic A.
Frederic A.

Reputation: 3514

I'm not sure what you refer to in Python, so details could help if the examples below don't match your expectations

A first one, make you go through the list twice:

List("cbda","xyz","jlki","badce").map(_.sorted).map {
  case even if even.length % 2 == 0 => even
  case odd => odd.reverse
}

Or makes you go through elements with even length twice:

List("cbda","xyz","jlki","badce").map {
  case even if even.length % 2 == 0 => even.sorted
  case odd => odd.sorted.reverse
}

Upvotes: 1

Related Questions