Wildcard generics of map() method

  • A+
Category:Languages

This is the implementation of map() method:

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {     Objects.requireNonNull(mapper);     if (!isPresent()) {         return empty();     } else {         return Optional.ofNullable(mapper.apply(value));     } } 

When I call map() like this, what is the type of T and U? What is the type of wildcard (?)? It is very confusing.

Optional<String> os1 = Optional.of("Optional String"); Optional<String> os2 = os1.map(s -> s.toUpperCase()); 

Javadoc statement says:

@param <U> is the type of the value returned from the mapping function.

Does "mapping function" mean map() method or argument of the map()?

 


Regardless if it's Stream or Optional, the purpose of the method map which accepts Function<? super T, ? extends U> is to map each input value T to an output of the same or different type U. The wildcard is used for extending the range of mapping possibilities.

Does "mapping function" mean map() method or argument of the map()?

The "mapping function" is a T -> U mapping implementation of an anonymous class of the Function interface which might be shortened with a lambda expression or a method reference.

In your sample, the T and U are both String since you map the String to its upper-case variation which is a String again. It behaves the same like UnaryOperator<T> a special case of Function<T, T> which consumes and returns the same type.

On the other hand, if you map:

os1.map(s -> s.length()) 
  • The T is String
  • The U is Integer since the method String::length produces an integer

You might shorten the lambda with a method reference:

Optional<String> os2 = os1.map(String::toUpperCase); 

... or better use both of the Optionals together:

Optional<String> os1 = Optional.of("Optional String");                                .map(String::toUpperCase); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: