Skip to content

Instantly share code, notes, and snippets.

@wsoczynski
Created March 16, 2013 20:13
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 wsoczynski/5178106 to your computer and use it in GitHub Desktop.
Save wsoczynski/5178106 to your computer and use it in GitHub Desktop.
public class FluentIterableExample {
public static void main(String... args){
List<Integer> input = generateInput();
EvenFilter evenFilter = new EvenFilter();
PowerFunction powerFunction = new PowerFunction(2);
RangeFilter rangeFilter = new RangeFilter(17, 50);
Optional<Double> result = FluentIterable.from(input).
filter(evenFilter).
transform(powerFunction).
firstMatch(rangeFilter);
return result.or(Double.valueOf(0));
}
private static List<Integer> generateInput(){
List<Integer> result = newLinkedList();
for(int i=1; i<101; i++){
result.add(i);
}
return result;
}
}
class EvenFilter implements Predicate<Integer> {
@Override
public boolean apply(Integer integer) {
return integer % 2 == 0;
}
}
class PowerFunction implements Function<Integer, Double> {
private final double root;
public PowerFunction(double root) {
this.root = root;
}
@Override
public Double apply(Integer input) {
return Math.pow(input, root);
}
}
class RangeFilter implements Predicate<Double> {
private final Range range;
public RangeFilter(int start, int end) {
this.range = Range.closed(Double.valueOf(start), Double.valueOf(end));
}
@Override
public boolean apply(Double input) {
return range.contains(input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment