What are practical uses of the java.util.function.Function.identity method?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
8
down vote

favorite
1












Why should I use Function.identity() when it returns the same thing which it receives without 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.










share|improve this question









New contributor




arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.























    up vote
    8
    down vote

    favorite
    1












    Why should I use Function.identity() when it returns the same thing which it receives without 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.










    share|improve this question









    New contributor




    arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















      up vote
      8
      down vote

      favorite
      1









      up vote
      8
      down vote

      favorite
      1






      1





      Why should I use Function.identity() when it returns the same thing which it receives without 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.










      share|improve this question









      New contributor




      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      Why should I use Function.identity() when it returns the same thing which it receives without 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.







      java java-8






      share|improve this question









      New contributor




      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 24 mins ago









      Boann

      35.7k1185116




      35.7k1185116






      New contributor




      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 6 hours ago









      arunveersingh

      413




      413




      New contributor




      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      arunveersingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          7
          down vote













          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());






          share|improve this answer




















          • @Eugene The implementation of identity() is return t -> t
            – Mark Rotteveel
            5 hours ago






          • 2




            @MarkRotteveel right. what I meant is this
            – Eugene
            5 hours ago











          • If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
            – Dici
            5 hours ago










          • @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
            – Eugene
            4 hours ago










          • @Dici it is 100% correct, under the current implementation at least, very easy to prove...
            – Eugene
            4 hours ago

















          up vote
          5
          down vote













          The intended usage is when you're using a method that accepts a Function to map something, and you need to map the input directly to the output of the function (the 'identity' function).



          As a very simple example, mapping a list of persons to a map from name to person:



          import static java.util.function.Function.identity

          // [...]

          List<Person> persons = ...
          Map<String, Person> = persons.stream()
          .collect(Collectors.toMap(Person::name, identity()))


          The identity() function is just for convenience and readability. As Peter indicates in his answer, you could just use t -> t, but personally I think that using identity() communicates intent better as it leaves no room for interpretation like wondering if the original author forgot to do a transformation in that lambda. I admit though that is highly subjective, and assumes the reader knows what identity() does.



          Possibly it may have some additional advantages in terms of memory as it reuses a single lambda definition, instead of having a specific lambda definition for this call. I think that impact is probably negligible in most cases.






          share|improve this answer





























            up vote
            1
            down vote













            Suppose you have a List<String> strings = List.of("abc", "de") and you want to generate a Map where Key is value form that List and Value is it's length:



             Map<String, Integer> map = strings.stream() 
            .collect(Collectors.toMap(Function.identity(), String::length))


            Generally some people see Function.identity() a little less readable than t -> t for example, but as explained here this is a bit different.






            share|improve this answer




















              Your Answer





              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: false,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );






              arunveersingh is a new contributor. Be nice, and check out our Code of Conduct.









               

              draft saved


              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52532565%2fwhat-are-practical-uses-of-the-java-util-function-function-identity-method%23new-answer', 'question_page');

              );

              Post as a guest






























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              7
              down vote













              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());






              share|improve this answer




















              • @Eugene The implementation of identity() is return t -> t
                – Mark Rotteveel
                5 hours ago






              • 2




                @MarkRotteveel right. what I meant is this
                – Eugene
                5 hours ago











              • If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
                – Dici
                5 hours ago










              • @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
                – Eugene
                4 hours ago










              • @Dici it is 100% correct, under the current implementation at least, very easy to prove...
                – Eugene
                4 hours ago














              up vote
              7
              down vote













              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());






              share|improve this answer




















              • @Eugene The implementation of identity() is return t -> t
                – Mark Rotteveel
                5 hours ago






              • 2




                @MarkRotteveel right. what I meant is this
                – Eugene
                5 hours ago











              • If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
                – Dici
                5 hours ago










              • @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
                – Eugene
                4 hours ago










              • @Dici it is 100% correct, under the current implementation at least, very easy to prove...
                – Eugene
                4 hours ago












              up vote
              7
              down vote










              up vote
              7
              down vote









              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());






              share|improve this answer












              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());







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 5 hours ago









              Peter Lawrey

              430k54539916




              430k54539916











              • @Eugene The implementation of identity() is return t -> t
                – Mark Rotteveel
                5 hours ago






              • 2




                @MarkRotteveel right. what I meant is this
                – Eugene
                5 hours ago











              • If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
                – Dici
                5 hours ago










              • @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
                – Eugene
                4 hours ago










              • @Dici it is 100% correct, under the current implementation at least, very easy to prove...
                – Eugene
                4 hours ago
















              • @Eugene The implementation of identity() is return t -> t
                – Mark Rotteveel
                5 hours ago






              • 2




                @MarkRotteveel right. what I meant is this
                – Eugene
                5 hours ago











              • If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
                – Dici
                5 hours ago










              • @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
                – Eugene
                4 hours ago










              • @Dici it is 100% correct, under the current implementation at least, very easy to prove...
                – Eugene
                4 hours ago















              @Eugene The implementation of identity() is return t -> t
              – Mark Rotteveel
              5 hours ago




              @Eugene The implementation of identity() is return t -> t
              – Mark Rotteveel
              5 hours ago




              2




              2




              @MarkRotteveel right. what I meant is this
              – Eugene
              5 hours ago





              @MarkRotteveel right. what I meant is this
              – Eugene
              5 hours ago













              If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
              – Dici
              5 hours ago




              If I had to implement a compiler for lambdas, I would make the lambda a synthetic, private static field (using an anonymous class) of the class declaring it unless it references variables which value will only be known at runtime. I'm not sure the answer you linked is 100% correct for cases where the lambda is self-contained.
              – Dici
              5 hours ago












              @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
              – Eugene
              4 hours ago




              @Dici that was btw a legal strategy that they initially wanted to go with (there are talks from Brian Goetz about this) - they choose not to. they choose to go with invokedynamic and generate the classes at runtime
              – Eugene
              4 hours ago












              @Dici it is 100% correct, under the current implementation at least, very easy to prove...
              – Eugene
              4 hours ago




              @Dici it is 100% correct, under the current implementation at least, very easy to prove...
              – Eugene
              4 hours ago












              up vote
              5
              down vote













              The intended usage is when you're using a method that accepts a Function to map something, and you need to map the input directly to the output of the function (the 'identity' function).



              As a very simple example, mapping a list of persons to a map from name to person:



              import static java.util.function.Function.identity

              // [...]

              List<Person> persons = ...
              Map<String, Person> = persons.stream()
              .collect(Collectors.toMap(Person::name, identity()))


              The identity() function is just for convenience and readability. As Peter indicates in his answer, you could just use t -> t, but personally I think that using identity() communicates intent better as it leaves no room for interpretation like wondering if the original author forgot to do a transformation in that lambda. I admit though that is highly subjective, and assumes the reader knows what identity() does.



              Possibly it may have some additional advantages in terms of memory as it reuses a single lambda definition, instead of having a specific lambda definition for this call. I think that impact is probably negligible in most cases.






              share|improve this answer


























                up vote
                5
                down vote













                The intended usage is when you're using a method that accepts a Function to map something, and you need to map the input directly to the output of the function (the 'identity' function).



                As a very simple example, mapping a list of persons to a map from name to person:



                import static java.util.function.Function.identity

                // [...]

                List<Person> persons = ...
                Map<String, Person> = persons.stream()
                .collect(Collectors.toMap(Person::name, identity()))


                The identity() function is just for convenience and readability. As Peter indicates in his answer, you could just use t -> t, but personally I think that using identity() communicates intent better as it leaves no room for interpretation like wondering if the original author forgot to do a transformation in that lambda. I admit though that is highly subjective, and assumes the reader knows what identity() does.



                Possibly it may have some additional advantages in terms of memory as it reuses a single lambda definition, instead of having a specific lambda definition for this call. I think that impact is probably negligible in most cases.






                share|improve this answer
























                  up vote
                  5
                  down vote










                  up vote
                  5
                  down vote









                  The intended usage is when you're using a method that accepts a Function to map something, and you need to map the input directly to the output of the function (the 'identity' function).



                  As a very simple example, mapping a list of persons to a map from name to person:



                  import static java.util.function.Function.identity

                  // [...]

                  List<Person> persons = ...
                  Map<String, Person> = persons.stream()
                  .collect(Collectors.toMap(Person::name, identity()))


                  The identity() function is just for convenience and readability. As Peter indicates in his answer, you could just use t -> t, but personally I think that using identity() communicates intent better as it leaves no room for interpretation like wondering if the original author forgot to do a transformation in that lambda. I admit though that is highly subjective, and assumes the reader knows what identity() does.



                  Possibly it may have some additional advantages in terms of memory as it reuses a single lambda definition, instead of having a specific lambda definition for this call. I think that impact is probably negligible in most cases.






                  share|improve this answer














                  The intended usage is when you're using a method that accepts a Function to map something, and you need to map the input directly to the output of the function (the 'identity' function).



                  As a very simple example, mapping a list of persons to a map from name to person:



                  import static java.util.function.Function.identity

                  // [...]

                  List<Person> persons = ...
                  Map<String, Person> = persons.stream()
                  .collect(Collectors.toMap(Person::name, identity()))


                  The identity() function is just for convenience and readability. As Peter indicates in his answer, you could just use t -> t, but personally I think that using identity() communicates intent better as it leaves no room for interpretation like wondering if the original author forgot to do a transformation in that lambda. I admit though that is highly subjective, and assumes the reader knows what identity() does.



                  Possibly it may have some additional advantages in terms of memory as it reuses a single lambda definition, instead of having a specific lambda definition for this call. I think that impact is probably negligible in most cases.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 5 hours ago

























                  answered 5 hours ago









                  Mark Rotteveel

                  56.6k1472111




                  56.6k1472111




















                      up vote
                      1
                      down vote













                      Suppose you have a List<String> strings = List.of("abc", "de") and you want to generate a Map where Key is value form that List and Value is it's length:



                       Map<String, Integer> map = strings.stream() 
                      .collect(Collectors.toMap(Function.identity(), String::length))


                      Generally some people see Function.identity() a little less readable than t -> t for example, but as explained here this is a bit different.






                      share|improve this answer
























                        up vote
                        1
                        down vote













                        Suppose you have a List<String> strings = List.of("abc", "de") and you want to generate a Map where Key is value form that List and Value is it's length:



                         Map<String, Integer> map = strings.stream() 
                        .collect(Collectors.toMap(Function.identity(), String::length))


                        Generally some people see Function.identity() a little less readable than t -> t for example, but as explained here this is a bit different.






                        share|improve this answer






















                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          Suppose you have a List<String> strings = List.of("abc", "de") and you want to generate a Map where Key is value form that List and Value is it's length:



                           Map<String, Integer> map = strings.stream() 
                          .collect(Collectors.toMap(Function.identity(), String::length))


                          Generally some people see Function.identity() a little less readable than t -> t for example, but as explained here this is a bit different.






                          share|improve this answer












                          Suppose you have a List<String> strings = List.of("abc", "de") and you want to generate a Map where Key is value form that List and Value is it's length:



                           Map<String, Integer> map = strings.stream() 
                          .collect(Collectors.toMap(Function.identity(), String::length))


                          Generally some people see Function.identity() a little less readable than t -> t for example, but as explained here this is a bit different.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 5 hours ago









                          Eugene

                          61.2k986143




                          61.2k986143




















                              arunveersingh is a new contributor. Be nice, and check out our Code of Conduct.









                               

                              draft saved


                              draft discarded


















                              arunveersingh is a new contributor. Be nice, and check out our Code of Conduct.












                              arunveersingh is a new contributor. Be nice, and check out our Code of Conduct.











                              arunveersingh is a new contributor. Be nice, and check out our Code of Conduct.













                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52532565%2fwhat-are-practical-uses-of-the-java-util-function-function-identity-method%23new-answer', 'question_page');

                              );

                              Post as a guest













































































                              Comments

                              Popular posts from this blog

                              Long meetings (6-7 hours a day): Being “babysat” by supervisor

                              What does second last employer means? [closed]

                              One-line joke