Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to sort a list of data classes by multiple columns in Scala

1 Answer

0 votes
case class Item(a: Int, b: Int, label: String)

object Main:

  // Sort by a, then b
  def sortData(items: List[Item]): List[Item] =
    items.sortBy(i => (i.a, i.b))

  // Print all items
  def printData(items: List[Item]): Unit =
    items.foreach(i => println(s"(${i.a}, ${i.b}, ${i.label})"))

  // Find first item by label
  def findByLabel(items: List[Item], label: String): Option[Item] =
    items.find(_.label == label)

  // Filter by a
  def filterByA(items: List[Item], value: Int): List[Item] =
    items.filter(_.a == value)

  def main(args: Array[String]): Unit =
    val data = List(
      Item(7, 2, "python"),
      Item(8, 3, "c"),
      Item(3, 5, "c++"),
      Item(4, 1, "c#"),
      Item(3, 2, "java"),
      Item(7, 1, "go"),
      Item(1, 2, "rust")
    )

    val sorted = sortData(data)
    println("Sorted data:")
    printData(sorted)

    println("\nSearching for 'java':")
    findByLabel(sorted, "java").foreach(println)

    println("\nFiltering items where a == 7:")
    val filtered = filterByA(sorted, 7)
    printData(filtered)

 
 
 
/*
run:
 
Sorted data:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)

Searching for 'java':
Item(3,2,java)

Filtering items where a == 7:
(7, 1, go)
(7, 2, python)
 
*/

 



answered Jan 29 by avibootz

Related questions

...