Skip to content

Instantly share code, notes, and snippets.

@santiagobasulto
Created April 4, 2012 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save santiagobasulto/2304539 to your computer and use it in GitHub Desktop.
Save santiagobasulto/2304539 to your computer and use it in GitHub Desktop.
Filtering collections on Scala
//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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment