Home > front end >  Scala Filtering List of Case Class
Scala Filtering List of Case Class

Time:12-09

Suppose you have a case class like below

case class Fruit(name: String, color: String, price: Double){
}

and you also have list of case class

val Fruits = List
(Fruit("Apple", "red", 3.00), Fruit ("Banana", "yellow", 4.99))

How do you filter based on name?

CodePudding user response:

Use the filter function to select the name attribute of the case class Fruit

scala> Fruits.filter(fruit => fruit.name == "Apple")
val res0: List[Fruit] = List(Fruit(Apple,red,3.0))

CodePudding user response:

List has a filter method.

case class Fruit(name: String, color: String, price: Double)

val Fruits = List(Fruit("Apple", "red", 3.00), Fruit ("Banana", "yellow", 4.99))

Fruits.filter(_.name == "Apple")
  • Related