Skip to content

Instantly share code, notes, and snippets.

@irof
Created December 1, 2012 05:58
Show Gist options
  • Save irof/4180737 to your computer and use it in GitHub Desktop.
Save irof/4180737 to your computer and use it in GitHub Desktop.
コレクションをアレコレするのをLambdaで書いてみた
List list = [
[color:"blue", weight:10],
[color:"red", weight:30],
[color:"blue", weight:50],
]
// groovy で Lambda を真似る
int weight = list
.findAll { it.color == 'blue' }
.collect { it.weight }
.inject(0) { acc, e -> acc + e }
assert weight == 60
// Groovyのを何パターンか書いてみる
// filter して map して reduce する
list.findAll { it.color == 'blue' }
.collect { it.weight }
.inject(0) { acc, e -> acc + e }
// 足すだけだったら sum がありますね
list.findAll { it.color == 'blue' }
.collect { it.weight }
.sum()
// weight引っぱりだすくらいならcollectなんていらない
list.findAll { it.color == 'blue' }.weight.sum()
// ところでsumってクロージャ引数にとれるんですよ
list.findAll { it.color == 'blue' }.sum { it.weight }
// 開き直るとsumだけで済んだりも……
list.sum { it.color == 'blue' ? it.weight : 0 }
import java.util.*;
public class Hoge {
static class Fuga {
final String color;
final int weight;
Fuga(String color, int weight) {
this.color = color;
this.weight = weight;
}
}
public static void main(String... args) {
List<Fuga> list = new ArrayList<>();
list.add(new Fuga("blue", 10));
list.add(new Fuga("red", 30));
list.add(new Fuga("blue", 50));
// Java SE 8 の Lambda で書くとこう
int weight = list.stream()
.filter( it -> it.color.equals("blue") )
.map( it -> it.weight )
.reduce(0, (acc, e) -> acc + e );
System.out.println(weight);
}
}
import java.util.*;
public class Hoge {
static class Fuga {
final String color;
final int weight;
Fuga(String color, int weight) {
this.color = color;
this.weight = weight;
}
}
public static void main(String... args) {
List<Fuga> list = new ArrayList<>();
list.add(new Fuga("blue", 10));
list.add(new Fuga("red", 30));
list.add(new Fuga("blue", 50));
// Java SE 7 以前の Java で書くとこんな感じ
int weight1 = 0;
for (Fuga e : list) {
if ("blue".equals(e.color)) {
weight1 += e.weight;
}
}
System.out.println(weight);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment