Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Last active August 29, 2015 14: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 mhewedy/2c2738d2ad4f7738d7f1 to your computer and use it in GitHub Desktop.
Save mhewedy/2c2738d2ad4f7738d7f1 to your computer and use it in GitHub Desktop.
Encapsulating behaviour using functional way
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> data = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Sum of Even Numbers: "
+ getTotal(data, new Functional<Integer>() {
public boolean test(Integer t) {
return t % 2 == 0;
}
}));
// ...etc..
}
private static int getTotal(List<Integer> list, Functional<Integer> func) {
int total = 0;
if (list != null) {
for (Integer intet : list) {
if (func.test(intet)) {
total += intet;
}
}
}
return total;
}
static interface Functional<T> {
boolean test(T t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment