Skip to content

Instantly share code, notes, and snippets.

@daiksy
Forked from irof/Hoge.java
Created December 1, 2012 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daiksy/4180777 to your computer and use it in GitHub Desktop.
Save daiksy/4180777 to your computer and use it in GitHub Desktop.
コレクションをぶんまわしてみる
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