Skip to content

Instantly share code, notes, and snippets.

@Kuchitama
Forked from irof/Hoge.java
Created December 1, 2012 06:09
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 Kuchitama/4180773 to your computer and use it in GitHub Desktop.
Save Kuchitama/4180773 to your computer and use it in GitHub Desktop.
コレクションをぶんまわしてみる
// Original source written by irof.
List list = [
[color:'blue', weight:10],
[color:'red', weight:30],
[color:'blue', weight:50],
]
// Javaで
int weight1 = 0;
for (def e : list) {
if (e.color == 'blue')
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 -> it.color == 'blue' }
.reduce (0, { acc, e -> acc + e.weight });
assert weight3 == 60
// こんな感じか?
// Scalaで
int weight4 = list.filter(_.color == "blue").reduce(_.weight + _.weight)
// Clojureで
// 多分間違ってるけどこんなイメージだよな
(def weight5 (->> list
(filter (= (% color "blue"))
(reduce + (first %) (rest %))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment