Functions in Java 8 are same as predicates but offer the flexibility to return any type of result, limited to a single value per function invocation. Oracle introduced the Function
interface in Java 8, housed within the java.util.function
package, to facilitate the implementation of functions in Java applications. This interface contains a single method, apply()
.
Difference Between Predicate and Function
Predicate in java 8
- Purpose: Used for conditional checks.
- Parameters: Accepts one parameter representing the input argument type (
Predicate<T>
). - Return Type: Returns a boolean value.
- Methods: Defines the
test()
method and includes default methods likeand()
,or()
, andnegate()
.
Functions in java 8
- Purpose: Performs operations and returns a result.
- Parameters: Accepts two type parameters: the input argument type and the return type (
Function<T, R>
). - Return Type: Can return any type of value.
- Methods: Defines the
apply()
method for computation.
Example: Finding the Square of a Number
Let’s write a function to calculate the square of a given integer:
import java.util.function.*;
class Test {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x;
System.out.println("Square of 5: " + square.apply(5)); // Output: Square of 5: 25
System.out.println("Square of -3: " + square.apply(-3)); // Output: Square of -3: 9
}
}
BiFunction
BiFunction is another useful functional interface in Java 8. It represents a function that accepts two arguments and produces a result. This is particularly useful when you need to combine or process two input values.
Example: Concatenating two strings
import java.util.function.*;
public class BiFunctionExample {
public static void main(String[] args) {
BiFunction<String, String, String> concat = (a, b) -> a + b;
System.out.println(concat.apply("Hello, ", "world!")); // Output: Hello, world!
}
}
Summary of Java 8 Functional Interfaces
- Predicate<T>:
- Purpose: Conditional checks.
- Method:
boolean test(T t)
- Example: Checking if a number is positive.
- Function<T, R>:
- Purpose: Transforming data.
- Method:
R apply(T t)
- Example: Converting a string to its length.
- BiFunction<T, U, R>:
- Purpose: Operations involving two inputs.
- Method:
R apply(T t, U u)
- Example: Adding two integers.
Conclusion
Java 8 functional interfaces like Predicate
, Function
, and BiFunction
offer powerful tools for developers to write more concise and readable code. Understanding the differences and appropriate use cases for each interface allows for better application design and implementation.
By using these interfaces, you can leverage the power of lambda expressions to create cleaner, more maintainable code. Whether you are performing simple conditional checks or more complex transformations, Java 8 has you covered.