scala order list
To order a list in Scala, you can use the sorted
method. This method sorts the elements of a collection in ascending order. Here's an example:
val myList = List(5, 3, 1, 4, 2)
val orderedList = myList.sorted
In this example, we have a list called myList
with elements [5, 3, 1, 4, 2]
. We call the sorted
method on myList
, which returns a new list orderedList
with elements [1, 2, 3, 4, 5]
. The original list myList
remains unchanged.
If you want to sort the list in descending order, you can use the reverse
method after calling sorted
:
val descendingList = myList.sorted.reverse
In this case, descendingList
will have elements [5, 4, 3, 2, 1]
.
You can also provide a custom ordering function to the sorted
method if you want to sort the list based on a specific criterion. For example, if you have a list of strings and you want to sort them based on their lengths, you can do the following:
val stringList = List("apple", "banana", "cat", "dog")
val orderedStringList = stringList.sorted(Ordering.by(_.length))
The Ordering.by(_.length)
function specifies that the elements should be sorted based on their lengths. In this case, orderedStringList
will have elements List("cat", "dog", "apple", "banana")
, as the strings are sorted in ascending order based on their lengths.
These are some ways you can order a list in Scala using the sorted
method.