5

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

John Barton
  • 1,581
  • 4
  • 25
  • 51
  • Related: https://softwareengineering.stackexchange.com/q/256090/3965 – Karl Bielefeldt Aug 29 '19 at 20:22
  • 1
    @AndyTurner bad example. Whether you use `.map(a -> a)` or `.map(Function.identity())`, the compiler will infer a `Function` in either case, as it has no hint that a supertype is intended. So the resulting stream type still is `Stream`. It does, however, infer the target list size for the `collect` operation from the assignment. Which works in both cases. You can map to a `Stream` with explicit types, like `.map(Function.identity())` or `.map(s -> s)` which again works in both cases. But `Function.identity()` doesn’t work with `mapToInt(i -> i)`… – Holger Aug 30 '19 at 08:05

1 Answers1

14

It's useful when the API forces you to pass a function, but all you want is to keep the original value.

For example, let's say you have a Stream<Country>, and you want to make turn it into a Map<String, Country>. You would use

stream.collect(Collectors.toMap(Country::getIsoCode, Function.identity()))

Collectors.toMap() expects a function to turn the Country into a key of the map, and another function to turn it into a value of the map. Since you want to store the country itself as value, you use the identity function.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255