Scala check if a ListBuffer[MyType] contains one element

1.6k views Asked by At

I have two class:

class Item(val description: String, val id: String) 

class ItemList {
  private var items : ListBuffer[Item] = ListBuffer()
}

How can I check if items contain one item with description=x and id=y?

3

There are 3 answers

0
Thilo On BEST ANSWER

That would be

list.exists(item => item.description == x && item.id == y)

If you also implement equals for your class (or even better, make it a case class which does that automatically), you can simplify that to

case class Item(description: String, id: String)
 // automatically everything a val, 
 // you get equals(), hashCode(), toString(), copy() for free
 // you don't need to say "new" to make instances

list.contains(Item(x,y))
0
Pedro Correia Luís On

Something like this:

def containsIdAndDescription(id: String, description: String) = {
   items.exists(item => item.id == id && item.description == description )
}
0
user2963757 On

Maybe think of these approaches, also:

//filter will return all elements which obey to filter condition

list.filter(item => item.description == x && item.id == y)

//find will return the fist element in the list

list.find(item => item.description == x && item.id == y)