UnaryOperator Interface in Java - Quiz
Total: 5 questions
1. When UnaryOperator interface can be used?
When UnaryOperator interface can be used?
It is used to work on a single operand and it returns the same type as an operand. The UnaryOperator can be used as lambda expression to pass as an argument.
2. Use UnaryOperator in lambda expression to convert string to upper case.
Use UnaryOperator in lambda expression to convert string to upper case.
UnaryOperator<String> uo = String::toUpperCase;
System.out.print(uo.apply("Ocpjp 8"));
3. The static method of the UnaryOperator interface.
The static method of the UnaryOperator interface.
static <T> UnaryOperator<T> identity()
4. How does UnaryOperator differ from Function, and why can a Function not be passed to List.replaceAll()?
How does UnaryOperator differ from Function, and why can a Function not be passed to List.replaceAll()?
Function<T, R> converts a value of one type into a value of another type (T -> R), while UnaryOperator<T> is the special case where the argument and the result share a type (T -> T). Inheritance runs one way only: UnaryOperator<T> extends Function<T, T> and not the reverse. So an operator can be handed to any method that expects a function (Stream.map(), for instance), but a function cannot be handed to a method whose contract demands an operator.
Function<String, String> trim = String::trim;
List<String> names = new ArrayList<>(List.of(" ann ", " bob"));
names.replaceAll(trim); // does not compile
names.replaceAll(trim::apply); // compiles: the method reference adapts it
5. What does andThen() return when it is called on a UnaryOperator?
What does andThen() return when it is called on a UnaryOperator?
A Function<T, V>, not a UnaryOperator<T>. UnaryOperator overrides neither andThen() nor compose(): both are inherited from Function together with their original return type, so composing two operators produces an ordinary function. When an operator is what you need, build the composition by hand in a lambda:
UnaryOperator<String> trim = String::trim;
Function<String, String> f = trim.andThen(String::toUpperCase); // fine
UnaryOperator<String> op = s -> trim.apply(s).toUpperCase(); // an operator again
The primitive variants (IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator) behave differently: their andThen() and compose() keep the original type.