Sobes.tech
Junior — Middle

Can you list the ways to use methods of the built-in functional interface in Java?

sobes.tech AI

Answer from AI

In Java, built-in functional interfaces (such as Function, Predicate, Consumer, Supplier) provide default methods and static methods that can be used for convenient work with functions.

Main ways to use methods of built-in functional interfaces:

  1. Default methods — allow combining or modifying the behavior of the interface without the need to create a new implementation. For example, Predicate has a method and(), which allows combining two predicates:
Predicate<String> isNotEmpty = s -> !s.isEmpty();
Predicate<String> startsWithA = s -> s.startsWith("A");
Predicate<String> combined = isNotEmpty.and(startsWithA);
boolean result = combined.test("Apple"); // true
  1. Static methods — provide helper functions for creating or working with functional interfaces. For example, Function.identity() returns a function that returns its argument unchanged:
Function<String, String> identity = Function.identity();
String result = identity.apply("test"); // "test"
  1. Function composition — using methods compose() and andThen() to create chains of transformations:
Function<Integer, Integer> multiplyBy2 = x -> x * 2;
Function<Integer, Integer> add3 = x -> x + 3;
Function<Integer, Integer> combined = multiplyBy2.andThen(add3);
int result = combined.apply(5); // (5 * 2) + 3 = 13

Thus, methods of built-in functional interfaces allow for convenient building and combining of functional operations, enhancing expressiveness and code readability.

Can you list the ways to use methods of the built-in… - sobes.tech