-
-
Save daiksy/4180777 to your computer and use it in GitHub Desktop.
コレクションをぶんまわしてみる
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
List list = [ | |
[color:"blue", weight:10], | |
[color:"red", weight:30], | |
[color:"blue", weight:50], | |
] | |
// Javaで | |
int weight1 = 0; | |
for (def e : list) { | |
if ("blue".equals(e.color)) | |
weight1 += e.weight; | |
} | |
assert weight1 == 60 | |
// groovyで | |
int weight2 = list | |
.findAll { it.color == 'blue' } | |
.inject(0) { acc, e -> acc + e.weight } | |
assert weight2 == 60 | |
// Lambdaだとこうなるっぽい? | |
int weight3 = list | |
.filter { it -> "blue".equals(it.color) } | |
.reduce (0, { (acc, e) -> acc + e.weight }); | |
assert weight3 == 60 | |
//Scalaだとこうだ! | |
val weight4: Int = list.filter(_.color == "blue").map(_.weight).sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment