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

2
  • Related: softwareengineering.stackexchange.com/q/256090/3965 Commented Aug 29, 2019 at 20:22
  • 1
    @AndyTurner bad example. Whether you use .map(a -> a) or .map(Function.identity()), the compiler will infer a Function<String,String> in either case, as it has no hint that a supertype is intended. So the resulting stream type still is Stream<String>. 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<Object> with explicit types, like .<Object>map(Function.identity()) or .<Object>map(s -> s) which again works in both cases. But Function.identity() doesn’t work with mapToInt(i -> i) Commented Aug 30, 2019 at 8:05

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.