What are practical usage of java.util.function.Function#identity method?

  • A+
Category:Languages

Why should I use Function.identity() when it returns the same thing which it receives without any scope of doing anything using the input or modifying the input in some way?

Apple apple = new Apple(10, "green"); Function<Apple, Apple> identity = Function.identity(); identity.apply(apple); 

There must be some practical usage of this which I am not able to figure out for sure.

 


You can use it for a frequency count for example.

public static <T> Map<T, Long> frequencyCount(Collection<T> words) {     return words.stream()             .collect(Collectors.groupingBy(Function.identity(),                     Collectors.counting()); } 

In this case, you are saying the key to group by is the element in the collection (without transforming it).

Personally, I find this briefer

import static java.util.stream.Collectors.*;  public static Map<String, Long> frequencyCount(Collection<String> words) {     return words.stream()             .collect(groupingBy(t -> t,                     counting()); } 

Comment

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