Archive

Archive for March 23, 2014

Java 8 : Predicate example

March 23, 2014 1 comment

Java 8 introduces functional style of programming.

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

Here we have list with integers, if we want to print even numbers from it, will write something like below


public List<Integer> printEvenNumbers(List<Integer> list){

List<Integer> result = new ArrayList<Integer>();

for(Integer i : list){

if(i%2 == 0){

result.add(i);

}

}

return result;

}

Now if we want to print odd numbers, so will write something like below


public List<Integer> printOddNumbers(List<Integer> list){

List<Integer> result = new ArrayList<Integer>();

for(Integer i : list){

if(i%2 != 0){

result.add(i);

}

}

return result;

}

Except the if condition, everything is copy pasted. Again if we want the numbers only divisible by 3, again we have to copy paste entire code just by changing the if condition.

If we have a chance to pass the if condition as a argument to method, then we would have achieved both requirements with only one method, for this java 8 introduced an interface called java.util.function.Predicate<T>

Complete example:


import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateTest{

public static void main(String [] a)  {

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

System.out.println("Print all numbers:");
condition(list, (n)->true);

System.out.println("Print no numbers:");
condition(list, (n)->false);

System.out.println("Print even numbers:");
condition(list, (n)-> n%2 == 0 );

System.out.println("Print odd numbers:");
condition(list, (n)-> n%2 == 1 );

System.out.println("Print numbers greater than 5:");
condition(list, (n)-> n > 5 );

}

public static void condition(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list)  {
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}

Advertisements
Categories: Java