Have been through some code and ran into Function.identity() which I found it is similar to s->s. I do not understand why and when I should use Function.identity().
I have tried to understand by working on an example, but it did not clarify my questions:
public static void main(String[] args){
Arrays.asList("a", "b", "c")
.stream()
.map(Function.identity())
//.map(str -> str) //it is the same as identity()
.forEach(System.out::println);
return;
}
When printing the list elements with and without mapping, I am getting the same result:
a
b
c
So, what is the purpose of including s-> s which is passing a string and retrieving an string? what is the purpose of Function.identity()?
Please provide me with a better example, maybe this example does not make sense to prove the importance of using identity().
Thanks
.map(a -> a)or.map(Function.identity()), the compiler will infer aFunction<String,String>in either case, as it has no hint that a supertype is intended. So the resulting stream type still isStream<String>. It does, however, infer the target list size for thecollectoperation from the assignment. Which works in both cases. You can map to aStream<Object>with explicit types, like.<Object>map(Function.identity())or.<Object>map(s -> s)which again works in both cases. ButFunction.identity()doesn’t work withmapToInt(i -> i)…