Java 8 Predicate with Examples
In Java 8, a Predicate , is a functional interface that represents a function that takes in an argument and returns a boolean value. The Predicate interface contains a single abstract method called test() that accepts an argument of a specified type and returns a boolean value.
Here's an example of how you can use the Predicate interface in Java 8:
Table of Content :
- Introduction
- what is Predicate in Java 8
- Predicate with filter()
- Predicate with &&
- Java 8 Predicate with or
- Predicate to Check employee belongs to particular City
- Summary
Predicate<Integergt isPositive = n -> n > 0;
System.out.println(isPositive.test(5)); // prints true
System.out.println(isPositive.test(-5)); // prints false
In this example, we define a Predicate named isPositive that tests if an integer value is greater than 0. We then use the test() method to test if the values 5 and -5 are positive.
The Predicate interface can be useful in a variety of scenarios, such as filtering data in collections, checking if an input is valid, and more. By providing a simple way to test whether a given condition is true or false, Predicates can simplify code and make it more expressive.
1 . Predicate with filter():
filter() accepts predicate as argument, and return the boolean result
package com.javacodestuffs.core.java8.streams.predicate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateFilterExample {
public static void main(String[] args) {
List<String> names = new ArrayList<> (Arrays.asList("Bala", "John", "Sara", "Joseph", "Lara", "Pramod"));
Predicate<String> startsWithJ = str -> str.startsWith("J");
List<String> filteredNames = names.stream().filter(startsWithJ).toList();
System.out.println(filteredNames); // prints [Joseph]
}
}
Output
[John, Joseph]
package com.javacodestuffs.core.java8.streams.predicate;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateFilterIntegerExample {
public static void main(String[] args) {
Predicate<Integer> greaterThanNine = x -> x > 9;
List<Integer> list = Arrays.asList(11, 12, 23, 4, 2, 45, 6, 7, 8, 9, 10);
List<Integer> collect = list.stream().filter(greaterThanNine).collect(Collectors.toList());
System.out.println(collect);
}
}
Output
[11, 12, 23, 45, 10]
2. Predicate with &&
package com.javacodestuffs.core.java8.streams.predicate; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class PredicateAndExample { public static void main(String[] args) { Predicate
greaterThanNine = x -> x > 9 && x%2==0; List list = Arrays.asList(11, 12, 23, 4, 2, 45, 6, 7, 8, 9, 10); List collect = list.stream().filter(greaterThanNine).collect(Collectors.toList()); System.out.println(collect); } }
Output
[12, 10]
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateAndExample1 {
public static void main(String[] args) {
Predicate<Integer> greaterThanNine = x -> x > 9;
Predicate<Integer> evenNumber = x -> x%2==0;
List<Integer> list = Arrays.asList(11, 12, 23, 4, 2, 45, 6, 7, 8, 9, 10);
List<Integer> collect = list.stream().filter(greaterThanNine.and(evenNumber)).collect(Collectors.toList());
System.out.println(collect);
}
}
Output
[12, 10]
3. Java 8 Predicate with or
1st Predicate evaluates whether number is even
2nd Predicate evaluates whether that same number is multiple 5
package com.javacodestuffs.core.java8.streams.predicate;
import java.util.function.Predicate;
public class PredicateWithOr {
public static void main(String[] args) {
Predicate<Integer> evenPredicate = i -> i % 2 == 0;
Predicate<Integer> multileofFivePredicate = i -> i % 5 == 0;
int numbers[] = { 15, 30, 25, 80, 65, 100, 101, 102 };
// check whether one of the predicates evaluates true
for (int num : numbers) {
if (evenPredicate.or(multileofFivePredicate).test(num)) {
System.out.println(num + " is either even or multiple of 5");
}
else
{
System.out.println(num + " is not even or multiple of 5 -------");
}
}
}
}
Output:
15 is either even or multiple of 5
30 is either even or multiple of 5
25 is either even or multiple of 5
80 is either even or multiple of 5
65 is either even or multiple of 5
100 is either even or multiple of 5
101 is not even or multiple of 5 -------
102 is either even or multiple of 5
4. Predicate to Check employee belongs to particular City
package com.javacodestuffs.core.java8.streams.predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class Employee {
String name;
int salary;
String email;
String city;
public Employee(String name, int salary, String email, String city) {
super();
this.name = name;
this.salary = salary;
this.email = email;
this.city = city;
}
@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + ", email=" + email + ", city=" + city + "]";
}
}
public class EmployeeTest {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Bala", 16500, "bala@gmail.com", "Mumbai"));
employees.add(new Employee("Sara", 5600, "sara@gmail.com", "Pune"));
employees.add(new Employee("John", 90500, "john@gmail.com", "Munich"));
employees.add(new Employee("Anand", 9700, "anand@gmail.com", "London"));
employees.add(new Employee("Saurabh", 10500, "saurabh@gmail.com", "Banglore"));
employees.add(new Employee("George", 16500, "george@gmail.com", "Mumbai"));
System.out.println("------------ Initial Employee list --------------------------------");
employees.forEach(System.out::println);
// lambda expression to check employee belongs to city Mumbai
Predicate<Employee> p = emp -> emp.city.equals("Mumbai");
employees.stream().filter(emp -> p.test(emp)).collect(Collectors.toList());
List<Employee> filteredEmployees = employees.stream().filter(emp -> p.test(emp)).collect(Collectors.toList());
System.out.println("------------ Employee list after applying Predicate ------------------");
filteredEmployees.forEach(System.out::println);
System.out.println("----------Iterating Employee list Predicate with predicate -----------");
for (Employee employee : employees) {
System.out.println("Whether '" + employee.name + "' leaves in city Mumbai: \t" + p.test(employee));
}
}
}
Output
------------ Initial Employee list --------------------------------
Employee [name=Bala, salary=16500, email=bala@gmail.com, city=Mumbai]
Employee [name=Sara, salary=5600, email=sara@gmail.com, city=Pune]
Employee [name=John, salary=90500, email=john@gmail.com, city=Munich]
Employee [name=Anand, salary=9700, email=anand@gmail.com, city=London]
Employee [name=Saurabh, salary=10500, email=saurabh@gmail.com, city=Banglore]
Employee [name=George, salary=16500, email=george@gmail.com, city=Mumbai]
------------ Employee list after applying Predicate ------------------
Employee [name=Bala, salary=16500, email=bala@gmail.com, city=Mumbai]
Employee [name=George, salary=16500, email=george@gmail.com, city=Mumbai]
----------Iterating Employee list Predicate with predicate -----------
Whether 'Bala' leaves in city Mumbai: true
Whether 'Sara' leaves in city Mumbai: false
Whether 'John' leaves in city Mumbai: false
Whether 'Anand' leaves in city Mumbai: false
Whether 'Saurabh' leaves in city Mumbai: false
Whether 'George' leaves in city Mumbai: true
Java 8 Predicate benefits
The introduction of the Predicate interface in Java 8 brought several benefits to the Java language and its developers.
- Code reuse and simplification: By defining a single method that accepts a parameter and returns a boolean value, the Predicate interface enables the creation of reusable code that can be used in a variety of scenarios.
- Functional programming: The Predicate interface is one of several functional interfaces introduced in Java 8. Functional programming allows developers to write code in a more declarative style, making it easier to reason about and debug.
- Stream API integration: The Stream API in Java 8 provides a powerful way to manipulate collections of data. By using Predicates with the filter() method, we can easily apply custom conditions to a collection and create a new collection that only includes elements that satisfy that condition.
- Improved readability: The use of Predicates can make code more expressive and easier to read. By using descriptive names for Predicates, we can create self-documenting code that is easy to understand.
- Overall, the introduction of the Predicate interface in Java 8 has made it easier for developers to write reusable, declarative, and readable code that integrates well with the Stream API.
Conclusion
In this article we have seen What is a Predicate in java 8 with examples along with its benefits to Java language and its developers.
0 Comments
Post a Comment