Java 8 : Predicates



Predicate Example to find out all the even numbers in the given array.


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.blogspot.ekumeedkiasha;

import java.util.function.Predicate;

/*
* find out all the even numbers in the given array
*/
public class PredicateExample2 {

public static void main(String[] args) {

int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Predicate<Integer> even = x -> x % 2 == 0;

for (int i : num) {
if (even.test(i)) {
System.out.println(i);
}
}

}

}




Predicate Joining Example:  

Interface predicate has three default methods.

1. and(Predicate p)
2. or(Predicate p)
3. negate()

find out all the even numbers which are greater than 5 in the given array.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.blogspot.ekumeedkiasha;

import java.util.function.Predicate;

/*
* Q1. Find out all the even numbers in the given array.
*
* Q2. Find out all the number which is greater than 5 in the given array.
*/
public class PredicateExample2 {

public static void main(String[] args) {

int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Predicate<Integer> even = x -> x % 2 == 0;

Predicate<Integer> grt = y -> y > 5;

for (int i : num) {
if (grt.or(even).test(i)) {
System.out.println(i);
}

}

}

}


For equality predicate interface has isEqual(Object o) method which is static.

Example: 
 1
2
3
4
5
6
7
8
9
10
11
12
package com.blogspot.ekumeedkiasha;

import java.util.function.Predicate;

public class PredicateExample3 {

public static void main(String[] args) {
Predicate<String> name = Predicate.isEqual("Mumbai");
System.out.println(name.test("Mumbai"));
}

}

Share this

Related Posts

Previous
Next Post »