public
Last active

Filtering collections on Scala

  • Download Gist
gistfile1.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//http://stackoverflow.com/questions/587404/java-finding-objects-in-collections
//http://stackoverflow.com/questions/122105/java-what-is-the-best-way-to-filter-a-collection
 
// Cat class definition
// I'm not kidding, nothing else is needed, but this is other topic
class Cat(val age: Int)
 
// With type inference and concise functional constructions
val a = Array(new Cat(age=1),new Cat(age=2))
// Filtering 1 year old cats
val age_1 = a.filter(_.age == 1)
print age_1 //Array[Cat] = Array(Cat@7596e2a5) (Needs toString method, but you get the point)
 
// Withot type inference and explicit functional constructions
val a:Array[Cat] = Array(new Cat(age=1),new Cat(age=2))
// Filtering 2 year old cats
val age_2 = a.filter((cat) => cat.age == 2)
print age_2 //Array[Cat] = Array(Cat@4f9faf3)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.