The intended usage is when you're using a method that accepts a Function
to map something, and you need to map the input directly to the output of the function (the 'identity' function).
As a very simple example, mapping a list of persons to a map from name to person:
import static java.util.function.Function.identity
// [...]
List<Person> persons = ...
Map<String, Person> = persons.stream()
.collect(Collectors.toMap(Person::name, identity()))
The identity()
function is just for convenience and readability. As Peter indicates in his answer, you could just use t -> t
, but personally I think that using identity()
communicates intent better as it leaves no room for interpretation like wondering if the original author forgot to do a transformation in that lambda. I admit though that is highly subjective, and assumes the reader knows what identity()
does.
Possibly it may have some additional advantages in terms of memory as it reuses a single lambda definition, instead of having a specific lambda definition for this call. I think that impact is probably negligible in most cases.