Jaba Interview
Jaba Interview
2. Updating counter
You can use a counter as a side effect if you need to track the number of times a function is
called or how many elements have been processed. This can be useful for metrics, analytics, or
just debugging.
3. Sending Notifications
When a certain condition is met, you might want to trigger a notification (like an email, SMS, or
push notification) as a side effect without altering the primary function’s result.
In this example, the main task is processing the order, but if the order is marked as high priority,
a notification (side effect) is sent to the relevant parties.
1. Predicate<T>:
• Takes: A single input (T).
• Does: Evaluates a condition or test on the input (T).
• Returns: A boolean (true or false) result.
• Use Case: When you need to perform a conditional check on data (like filtering or
validation).
• Example:
Predicate<Integer> isEven = n -> n % 2 == 0;
boolean result = isEven.test(4); // Returns true (4 is even)
2. Consumer<T>:
• Takes: A single input (T).
• Does: Performs an action on the input (side effects).
• Returns: No result (void).
• Use Case: When you want to process the data but don’t need to return a
result.
• Example:
Consumer<String> print = s -> System.out.println(s);
print.accept("Hello"); // Prints "Hello"
3. Function<T, R>:
• Takes: A single input (T).
• Does: Transforms the input into a result (R).
• Returns: A result (R).
• Use Case: When you want to transform or map an input to a result.
• Example:
Function<String, Integer> lengthFunction = s -> s.length();
int length = lengthFunction.apply("Hello"); // Returns 5
4. Supplier<R>:
• Takes: No input.
• Does: Produces a result (R), often on demand.
• Returns: A result (R).
• Use Case: When you need to supply or generate values without any input,
such as generating random numbers or getting the current time.
• Example: