Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list in Scala by two fields?

how to sort a list in Scala by two fields, in this example I will sort by lastName and firstName?

case class Row(var firstName: String, var lastName: String, var city: String)  var rows = List(new Row("Oscar", "Wilde", "London"),                 new Row("Otto",  "Swift", "Berlin"),                 new Row("Carl",  "Swift", "Paris"),                 new Row("Hans",  "Swift", "Dublin"),                 new Row("Hugo",  "Swift", "Sligo"))  rows.sortBy(_.lastName) 

I try things like this

rows.sortBy(_.lastName + _.firstName) 

but it doesn't work. So I be curious for a good and easy solution.

like image 925
Twistleton Avatar asked Apr 05 '12 11:04

Twistleton


People also ask

How to sort the list in Scala?

Use the sortWith() Function to Sort List in Scala. We used the sortWith() function to take a lambda expression as an argument and return the sorted result. We can use this function to sort the list in ascending and descending order.

How do you sort a set in Scala?

The first two methods that are used here ("SortedSet" and "TreeSet") are used to sort immutable sets in Scala and take set as input and return the sorted set. The last method is SortedSet working over mutable sets too and take the list conversion of the set to sort.


2 Answers

rows.sortBy(r => (r.lastName, r.firstName)) 
like image 70
senia Avatar answered Sep 19 '22 02:09

senia


rows.sortBy (row => row.lastName + row.firstName) 

If you want to sort by the merged names, as in your question, or

rows.sortBy (row => (row.lastName, row.firstName)) 

if you first want to sort by lastName, then firstName; relevant for longer names (Wild, Wilder, Wilderman).

If you write

rows.sortBy(_.lastName + _.firstName) 

with 2 underlines, the method expects two parameters:

<console>:14: error: wrong number of parameters; expected = 1        rows.sortBy (_.lastName + _.firstName)                                ^ 
like image 30
user unknown Avatar answered Sep 23 '22 02:09

user unknown