-
-
Save cocoatomo/4380714 to your computer and use it in GitHub Desktop.
using Guava
This file contains 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
package net.elliptium; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.List; | |
import com.google.common.base.Function; | |
import com.google.common.base.Predicate; | |
import com.google.common.collect.Collections2; | |
public class Hoge { | |
static class Fuga { | |
final String color; | |
final int weight; | |
Fuga(String color, int weight) { | |
this.color = color; | |
this.weight = weight; | |
} | |
} | |
private static class FugaColorFilter implements Predicate<Fuga> { | |
String color; | |
public FugaColorFilter(String color) { | |
this.color = color; | |
} | |
public boolean apply(Fuga fuga) { | |
return this.color.equals(fuga.color); | |
} | |
@Override | |
public boolean equals(Object object) { | |
if (!(object instanceof Fuga)) { | |
return false; | |
} | |
Fuga that = (Fuga) object; | |
return this.color.equals(that.color); | |
} | |
} | |
private static class FugaWeightMapper implements Function<Fuga, Integer> { | |
public Integer apply(Fuga input) { | |
return (Integer) input.weight; | |
} | |
@Override | |
public boolean equals(Object object) { | |
return object instanceof FugaWeightMapper; | |
} | |
} | |
private interface FoldFunction<T, F> { | |
T apply(T acc, F object); | |
boolean equals(Object object); | |
} | |
private static class Collections3 { | |
static <T, F> T fold(Collection<F> unfolded, T initialValue, FoldFunction<T, F> foldFunction) { | |
T result = initialValue; | |
for (F element : unfolded) { | |
result = foldFunction.apply(result, element); | |
} | |
return result; | |
} | |
} | |
private static class IntegerAddition implements FoldFunction<Integer, Integer> { | |
public Integer apply(Integer acc, Integer object) { | |
return acc + object; | |
} | |
@Override | |
public boolean equals(Object object) { | |
return object instanceof IntegerAddition; | |
} | |
} | |
public static void main(String... args) { | |
List<Fuga> list = new ArrayList<Fuga>(); | |
list.add(new Fuga("blue", 10)); | |
list.add(new Fuga("red", 30)); | |
list.add(new Fuga("blue", 50)); | |
// Guava で書くとこう. 一部自作あり. | |
int weight = | |
Collections3.fold( | |
Collections2.transform( | |
Collections2.filter(list, new FugaColorFilter("blue")), | |
new FugaWeightMapper()), | |
0, | |
new IntegerAddition()); | |
System.out.println(weight); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment