Introduction to Java Predefined Functional Interfaces
Jashwanth Jampala
Software Engineer @ People Tech Group | Java Full-Stack Developer | Java , Spring Boot, Microservices, Python, React, SQL, NoSQL, AWS | Open to New Opportunities
Hi everyone! Today, I’m excited to discuss some of the predefined functional interfaces in Java that are commonly used with Stream APIs. Let’s dive into four main functional interfaces:
1) Predicate
Description: A functional interface used primarily for conditional checks.
Method: boolean test(T t)
Details: The 'test' method takes one parameter and returns a boolean value. It is often used in filtering operations in streams.
Example:
Interface | Method |
Predicate<T> | boolean test(T t) |
Predicate<Integer> isGreaterThan500 = i -> i > 500;
System.out.println(isGreaterThan500.test(600)); // true
2) Function
Description: This interface is used to apply operations on a given input and produce a result.
Method: R apply(T t)
Details: The 'apply' method takes one parameter and returns a value of any specified type. It's versatile and used for transforming data in streams.
Example:
Interface | Method |
Function <T,R> | R apply(T t) |
Function<String, Integer> stringLength = s -> s.length();
System.out.println(stringLength.apply("Hello")); // 5
领英推荐
3) Consumer
Description: The Consumer interface represents an operation that accepts a single input argument and returns no result.
Method: void accept(T t)
Details: The 'accept' method takes one parameter and does not return any value. It's commonly used for performing operations like printing or logging the values.
Example:
Interface | Method |
Consumer<T> | void accept (T t) |
Consumer<String> printString = s->System.out.println(s);
printString.accept("Hello, World!");
4) Supplier
Description: This interface is used to supply values without taking any input.
Method: T get()
Details: The 'get' method doesn't take any parameters and returns a value. It's often used for generating values, such as current dates or random numbers.
Example:
Interface | Method |
Supplier<T> |T get () |
Supplier<Date> currentDate = () -> new Date ();
System.out.println(currentDate.get());
These predefined functional interfaces are foundational in Java's functional programming capabilities, especially when working with streams. Understanding and utilizing them effectively can significantly improve the readability and maintainability of your code.
Data(AI/ML) at Meta |Ex-Amazon | Ex-Vice President UB AI | Tableau Desktop certified| #OpenToOpportunities
9 个月That’s informative, keep going Jashwanth Jampala