when to use Identity function in Java?

Juan Perez :

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

JB Nizet :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326174&siteId=1