Hari
Hari

Reputation: 13

how to sort List objects based on the object fields in Scala?

I have a List of objects(for example, Student(Name: String, RollNo: Int)) and is there a way to sort them in Scala?

Thanks in advance.

Upvotes: 1

Views: 916

Answers (2)

Gal Naor
Gal Naor

Reputation: 2397

You can do this:

case class Student(name: String, rollNo: Int)

val list = List(Student("bbb",1), Student("aaa",1))

val sortedList = list.sortBy(_.name)

or choose the rollNo property.

Upvotes: 1

Sai Gowtham Badvity
Sai Gowtham Badvity

Reputation: 46

You can use sortWith() function or Ordered trait to sort the List objects. check out the below link:

Sorting a List of custom objects using sortWith function in Scala

Upvotes: 3

Related Questions