Created
March 16, 2013 20:13
-
-
Save wsoczynski/5178106 to your computer and use it in GitHub Desktop.
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
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