Created
April 4, 2012 18:30
-
-
Save santiagobasulto/2304539 to your computer and use it in GitHub Desktop.
Filtering collections on Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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