Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Java 8 introduced functional interfaces and lambda expressions to simplify the manipulation of collections. One such functional interface is Predicate
, which represents a boolean-valued function of one argument. You can use Predicate
along with the Stream
API and lambda expressions to filter, modify, or query collections in a more concise and readable way. Here's a tutorial on using Java 8's Predicate
to manipulate collections.
First, import the necessary classes from the java.util
and java.util.function
packages.
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors;
Create a sample collection, such as a List
of integers, to demonstrate the use of Predicate
.
List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5);
Define a Predicate
using a lambda expression. For example, create a predicate that checks whether a number is even.
Predicate<Integer> isEven = n -> n % 2 == 0;
You can use the Stream
API's filter()
method along with a Predicate
to filter elements in a collection. For example, create a new list containing only the even numbers from the numbers
list.
List<Integer> evenNumbers = numbers.stream() .filter(isEven) .collect(Collectors.toList()); System.out.println(evenNumbers); // Output: [2, 4]
You can also combine multiple predicates using the and()
, or()
, and negate()
methods. For example, create two predicates to check whether a number is even and greater than 2, and then filter the list using both predicates.
Predicate<Integer> isEven = n -> n % 2 == 0; Predicate<Integer> greaterThanTwo = n -> n > 2; // Combine predicates Predicate<Integer> evenAndGreaterThanTwo = isEven.and(greaterThanTwo); List<Integer> filteredNumbers = numbers.stream() .filter(evenAndGreaterThanTwo) .collect(Collectors.toList()); System.out.println(filteredNumbers); // Output: [4]
This tutorial demonstrated how to use Java 8's Predicate
functional interface and the Stream
API to manipulate collections. By leveraging Predicate
and lambda expressions, you can write more concise and readable code when filtering, modifying, or querying collections.