How do Java 8 default methods hеlp with lambdas?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







22















It is claimed in this article that:




one of the major reasons for introducing default methods in
interfaces is to enhance the Collections API in Java 8 to support
lambda expressions.




I could understand that the @FunctionalInterface helped by saying that there is ONLY one abstract method and the lambda should represent this particular method.



But how is it that the default methods helped to support lambdas?










share|improve this question































    22















    It is claimed in this article that:




    one of the major reasons for introducing default methods in
    interfaces is to enhance the Collections API in Java 8 to support
    lambda expressions.




    I could understand that the @FunctionalInterface helped by saying that there is ONLY one abstract method and the lambda should represent this particular method.



    But how is it that the default methods helped to support lambdas?










    share|improve this question



























      22












      22








      22


      2






      It is claimed in this article that:




      one of the major reasons for introducing default methods in
      interfaces is to enhance the Collections API in Java 8 to support
      lambda expressions.




      I could understand that the @FunctionalInterface helped by saying that there is ONLY one abstract method and the lambda should represent this particular method.



      But how is it that the default methods helped to support lambdas?










      share|improve this question
















      It is claimed in this article that:




      one of the major reasons for introducing default methods in
      interfaces is to enhance the Collections API in Java 8 to support
      lambda expressions.




      I could understand that the @FunctionalInterface helped by saying that there is ONLY one abstract method and the lambda should represent this particular method.



      But how is it that the default methods helped to support lambdas?







      java






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 21 at 12:24









      Boann

      37.9k1291123




      37.9k1291123










      asked Apr 21 at 7:39









      mCsmCs

      6521935




      6521935
























          3 Answers
          3






          active

          oldest

          votes


















          34














          To give you an example take the case of the Collection.forEach method, which is designed to take an instance of the Consumer functional interface and has a default implementation in the Collection interface:



          default void forEach(Consumer<? super T> action) {
          Objects.requireNonNull(action);
          for (T t : this) {
          action.accept(t);
          }
          }


          If the JDK designers didn't introduce the concept of default methods then all the implementing classes of the Collection interface would have to implement the forEach method so it would be problematic to switch to Java - 8 without breaking your code.



          So to facilitate the adoption of lambdas and the use of the new functional interfaces like Consumer, Supplier, Predicate, etc. the JDK designers introduced the concept of default methods to provide backward compatibility and it is now easier to switch to Java - 8 without making any changes.



          If you don't like the default implementation in the interface you can override it and supply your own.






          share|improve this answer


























          • Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

            – dorony
            Apr 26 at 17:35





















          14














          They helped indirectly: you can use lambdas on collections thanks to additional methods like removeIf(), stream(), etc.



          Those methods couldn't have been added to collections without completely breaking existing collection implementations if they had not been added as default methods.






          share|improve this answer































            4














            Another situation where default methods help a ton is in the functional interfaces themself. Take the Function<T,R> interface for example, the only method you really care about is R apply(T t), so when you need a Functionsomewhere, you can pass a lambda and it will create a Function instance where that lambda method is the apply method.



            However once you have a Function instance, you can call other useful methods like <V> Function<T,V> andThen(Function<? super R,? extends V> after) that combine functions on them. The default implementation is simply chaining the functions, but you can override it if you create your own class implementing the Function interface.



            In short, default methods give you an easy way to create lambdas from functional interfaces that have additinal methods, while giving you the option to override those additinal methods in with a full class if you need to.






            share|improve this answer
























            • In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

              – OrangeDog
              Apr 22 at 9:04











            • I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

              – Marco13
              Apr 22 at 18:07














            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',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55780860%2fhow-do-java-8-default-methods-h%25d0%25b5lp-with-lambdas%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            34














            To give you an example take the case of the Collection.forEach method, which is designed to take an instance of the Consumer functional interface and has a default implementation in the Collection interface:



            default void forEach(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            for (T t : this) {
            action.accept(t);
            }
            }


            If the JDK designers didn't introduce the concept of default methods then all the implementing classes of the Collection interface would have to implement the forEach method so it would be problematic to switch to Java - 8 without breaking your code.



            So to facilitate the adoption of lambdas and the use of the new functional interfaces like Consumer, Supplier, Predicate, etc. the JDK designers introduced the concept of default methods to provide backward compatibility and it is now easier to switch to Java - 8 without making any changes.



            If you don't like the default implementation in the interface you can override it and supply your own.






            share|improve this answer


























            • Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

              – dorony
              Apr 26 at 17:35


















            34














            To give you an example take the case of the Collection.forEach method, which is designed to take an instance of the Consumer functional interface and has a default implementation in the Collection interface:



            default void forEach(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            for (T t : this) {
            action.accept(t);
            }
            }


            If the JDK designers didn't introduce the concept of default methods then all the implementing classes of the Collection interface would have to implement the forEach method so it would be problematic to switch to Java - 8 without breaking your code.



            So to facilitate the adoption of lambdas and the use of the new functional interfaces like Consumer, Supplier, Predicate, etc. the JDK designers introduced the concept of default methods to provide backward compatibility and it is now easier to switch to Java - 8 without making any changes.



            If you don't like the default implementation in the interface you can override it and supply your own.






            share|improve this answer


























            • Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

              – dorony
              Apr 26 at 17:35
















            34












            34








            34







            To give you an example take the case of the Collection.forEach method, which is designed to take an instance of the Consumer functional interface and has a default implementation in the Collection interface:



            default void forEach(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            for (T t : this) {
            action.accept(t);
            }
            }


            If the JDK designers didn't introduce the concept of default methods then all the implementing classes of the Collection interface would have to implement the forEach method so it would be problematic to switch to Java - 8 without breaking your code.



            So to facilitate the adoption of lambdas and the use of the new functional interfaces like Consumer, Supplier, Predicate, etc. the JDK designers introduced the concept of default methods to provide backward compatibility and it is now easier to switch to Java - 8 without making any changes.



            If you don't like the default implementation in the interface you can override it and supply your own.






            share|improve this answer















            To give you an example take the case of the Collection.forEach method, which is designed to take an instance of the Consumer functional interface and has a default implementation in the Collection interface:



            default void forEach(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            for (T t : this) {
            action.accept(t);
            }
            }


            If the JDK designers didn't introduce the concept of default methods then all the implementing classes of the Collection interface would have to implement the forEach method so it would be problematic to switch to Java - 8 without breaking your code.



            So to facilitate the adoption of lambdas and the use of the new functional interfaces like Consumer, Supplier, Predicate, etc. the JDK designers introduced the concept of default methods to provide backward compatibility and it is now easier to switch to Java - 8 without making any changes.



            If you don't like the default implementation in the interface you can override it and supply your own.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 21 at 19:13









            Oleksandr

            9,84544372




            9,84544372










            answered Apr 21 at 7:52









            Amardeep BhowmickAmardeep Bhowmick

            6,53621231




            6,53621231













            • Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

              – dorony
              Apr 26 at 17:35





















            • Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

              – dorony
              Apr 26 at 17:35



















            Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

            – dorony
            Apr 26 at 17:35







            Adding default methods to java interfaces probably did brake existing java code, for example: if a class in java 7 has an int sort() method and also implements Collection, and now there is a default void sort() method in Collection, then the existing class will no longer compile in java 8. I guess that the JDK designers took that into account and chose the best option they had at the time.

            – dorony
            Apr 26 at 17:35















            14














            They helped indirectly: you can use lambdas on collections thanks to additional methods like removeIf(), stream(), etc.



            Those methods couldn't have been added to collections without completely breaking existing collection implementations if they had not been added as default methods.






            share|improve this answer




























              14














              They helped indirectly: you can use lambdas on collections thanks to additional methods like removeIf(), stream(), etc.



              Those methods couldn't have been added to collections without completely breaking existing collection implementations if they had not been added as default methods.






              share|improve this answer


























                14












                14








                14







                They helped indirectly: you can use lambdas on collections thanks to additional methods like removeIf(), stream(), etc.



                Those methods couldn't have been added to collections without completely breaking existing collection implementations if they had not been added as default methods.






                share|improve this answer













                They helped indirectly: you can use lambdas on collections thanks to additional methods like removeIf(), stream(), etc.



                Those methods couldn't have been added to collections without completely breaking existing collection implementations if they had not been added as default methods.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 21 at 7:49









                JB NizetJB Nizet

                554k629081031




                554k629081031























                    4














                    Another situation where default methods help a ton is in the functional interfaces themself. Take the Function<T,R> interface for example, the only method you really care about is R apply(T t), so when you need a Functionsomewhere, you can pass a lambda and it will create a Function instance where that lambda method is the apply method.



                    However once you have a Function instance, you can call other useful methods like <V> Function<T,V> andThen(Function<? super R,? extends V> after) that combine functions on them. The default implementation is simply chaining the functions, but you can override it if you create your own class implementing the Function interface.



                    In short, default methods give you an easy way to create lambdas from functional interfaces that have additinal methods, while giving you the option to override those additinal methods in with a full class if you need to.






                    share|improve this answer
























                    • In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

                      – OrangeDog
                      Apr 22 at 9:04











                    • I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

                      – Marco13
                      Apr 22 at 18:07


















                    4














                    Another situation where default methods help a ton is in the functional interfaces themself. Take the Function<T,R> interface for example, the only method you really care about is R apply(T t), so when you need a Functionsomewhere, you can pass a lambda and it will create a Function instance where that lambda method is the apply method.



                    However once you have a Function instance, you can call other useful methods like <V> Function<T,V> andThen(Function<? super R,? extends V> after) that combine functions on them. The default implementation is simply chaining the functions, but you can override it if you create your own class implementing the Function interface.



                    In short, default methods give you an easy way to create lambdas from functional interfaces that have additinal methods, while giving you the option to override those additinal methods in with a full class if you need to.






                    share|improve this answer
























                    • In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

                      – OrangeDog
                      Apr 22 at 9:04











                    • I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

                      – Marco13
                      Apr 22 at 18:07
















                    4












                    4








                    4







                    Another situation where default methods help a ton is in the functional interfaces themself. Take the Function<T,R> interface for example, the only method you really care about is R apply(T t), so when you need a Functionsomewhere, you can pass a lambda and it will create a Function instance where that lambda method is the apply method.



                    However once you have a Function instance, you can call other useful methods like <V> Function<T,V> andThen(Function<? super R,? extends V> after) that combine functions on them. The default implementation is simply chaining the functions, but you can override it if you create your own class implementing the Function interface.



                    In short, default methods give you an easy way to create lambdas from functional interfaces that have additinal methods, while giving you the option to override those additinal methods in with a full class if you need to.






                    share|improve this answer













                    Another situation where default methods help a ton is in the functional interfaces themself. Take the Function<T,R> interface for example, the only method you really care about is R apply(T t), so when you need a Functionsomewhere, you can pass a lambda and it will create a Function instance where that lambda method is the apply method.



                    However once you have a Function instance, you can call other useful methods like <V> Function<T,V> andThen(Function<? super R,? extends V> after) that combine functions on them. The default implementation is simply chaining the functions, but you can override it if you create your own class implementing the Function interface.



                    In short, default methods give you an easy way to create lambdas from functional interfaces that have additinal methods, while giving you the option to override those additinal methods in with a full class if you need to.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Apr 21 at 14:46









                    kajacxkajacx

                    7,71142754




                    7,71142754













                    • In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

                      – OrangeDog
                      Apr 22 at 9:04











                    • I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

                      – Marco13
                      Apr 22 at 18:07





















                    • In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

                      – OrangeDog
                      Apr 22 at 9:04











                    • I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

                      – Marco13
                      Apr 22 at 18:07



















                    In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

                    – OrangeDog
                    Apr 22 at 9:04





                    In that case an abstract class would've achieved the same thing (though removing the opportunity to extend another class).

                    – OrangeDog
                    Apr 22 at 9:04













                    I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

                    – Marco13
                    Apr 22 at 18:07







                    I consider this as the most crucial point (At least referring to the quoted statement and question title on a language level - not so much on the (collections) API level) : Namely, that you can have an interface with multiple methods, but still "implement" it via a lambda expression if and only if it has a single abstract method (in fact, in the beginning, these types had been referred to as "SAM Types" or "Single Abstract Method Types").

                    – Marco13
                    Apr 22 at 18:07




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55780860%2fhow-do-java-8-default-methods-h%25d0%25b5lp-with-lambdas%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

                    Bunad

                    Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum