Last active
August 29, 2015 14:09
-
-
Save mhewedy/2c2738d2ad4f7738d7f1 to your computer and use it in GitHub Desktop.
Encapsulating behaviour using functional way
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
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