How do Java 8 default methods hеlp with lambdas? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Does Java support default parameter values?How do I convert a String to an int in Java?Creating a memory leak with JavaHow should I have explained the difference between an Interface and an Abstract class?Why is “final” not allowed in Java 8 interface methods?

Can the van der Waals coefficients be negative in the van der Waals equation for real gases?

Lights are flickering on and off after accidentally bumping into light switch

What is the definining line between a helicopter and a drone a person can ride in?

Why aren't these two solutions equivalent? Combinatorics problem

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

Pointing to problems without suggesting solutions

Why do some non-religious people reject artificial consciousness?

Does using the Inspiration rules for character defects encourage My Guy Syndrome?

How can I introduce the names of fantasy creatures to the reader?

Has a Nobel Peace laureate ever been accused of war crimes?

How to mute a string and play another at the same time

Why is one lightbulb in a string illuminated?

A journey... into the MIND

Determine the generator of an ideal of ring of integers

Is my guitar’s action too high?

Kepler's 3rd law: ratios don't fit data

What's the difference between using dependency injection with a container and using a service locator?

Should man-made satellites feature an intelligent inverted "cow catcher"?

tabularx column has extra padding at right?

Who can become a wight?

How to ask rejected full-time candidates to apply to teach individual courses?

Unix AIX passing variable and arguments to expect and spawn

Does GDPR cover the collection of data by websites that crawl the web and resell user data

What helicopter has the most rotor blades?



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



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Does Java support default parameter values?How do I convert a String to an int in Java?Creating a memory leak with JavaHow should I have explained the difference between an Interface and an Abstract class?Why is “final” not allowed in Java 8 interface methods?



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








15















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






























    15















    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


























      15












      15








      15


      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 yesterday









      Boann

      37.6k1291123




      37.6k1291123










      asked yesterday









      mCsmCs

      6211832




      6211832






















          4 Answers
          4






          active

          oldest

          votes


















          26














          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
































            13














            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
                16 hours ago











              • 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
                7 hours ago



















              0














              While this is a great question and there are already insightful answers but you should be very careful with adding default method to any existing interfaces.



              And, I take this from Effective Java - Item 21: Design interfaces with posterity the following words :




              But it is not always possible to write a default method that maintains all invariants of every conceivable implementation.




              Although adding a default method to an existing interface facilitate backwards compatibility but the primary goal of adding this was to allow clients to ease use new interface without having to write their own implementation.






              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',
                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

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                26














                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





























                  26














                  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



























                    26












                    26








                    26







                    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 yesterday









                    Oleksandr

                    9,64044372




                    9,64044372










                    answered yesterday









                    Amardeep BhowmickAmardeep Bhowmick

                    6,39121231




                    6,39121231























                        13














                        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



























                          13














                          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

























                            13












                            13








                            13







                            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 yesterday









                            JB NizetJB Nizet

                            550k618981025




                            550k618981025





















                                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
                                  16 hours ago











                                • 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
                                  7 hours ago
















                                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
                                  16 hours ago











                                • 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
                                  7 hours ago














                                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 yesterday









                                kajacxkajacx

                                7,59642754




                                7,59642754












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

                                  – OrangeDog
                                  16 hours ago











                                • 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
                                  7 hours ago


















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

                                  – OrangeDog
                                  16 hours ago











                                • 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
                                  7 hours ago

















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

                                – OrangeDog
                                16 hours ago





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

                                – OrangeDog
                                16 hours ago













                                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
                                7 hours ago






                                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
                                7 hours ago












                                0














                                While this is a great question and there are already insightful answers but you should be very careful with adding default method to any existing interfaces.



                                And, I take this from Effective Java - Item 21: Design interfaces with posterity the following words :




                                But it is not always possible to write a default method that maintains all invariants of every conceivable implementation.




                                Although adding a default method to an existing interface facilitate backwards compatibility but the primary goal of adding this was to allow clients to ease use new interface without having to write their own implementation.






                                share|improve this answer



























                                  0














                                  While this is a great question and there are already insightful answers but you should be very careful with adding default method to any existing interfaces.



                                  And, I take this from Effective Java - Item 21: Design interfaces with posterity the following words :




                                  But it is not always possible to write a default method that maintains all invariants of every conceivable implementation.




                                  Although adding a default method to an existing interface facilitate backwards compatibility but the primary goal of adding this was to allow clients to ease use new interface without having to write their own implementation.






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    While this is a great question and there are already insightful answers but you should be very careful with adding default method to any existing interfaces.



                                    And, I take this from Effective Java - Item 21: Design interfaces with posterity the following words :




                                    But it is not always possible to write a default method that maintains all invariants of every conceivable implementation.




                                    Although adding a default method to an existing interface facilitate backwards compatibility but the primary goal of adding this was to allow clients to ease use new interface without having to write their own implementation.






                                    share|improve this answer













                                    While this is a great question and there are already insightful answers but you should be very careful with adding default method to any existing interfaces.



                                    And, I take this from Effective Java - Item 21: Design interfaces with posterity the following words :




                                    But it is not always possible to write a default method that maintains all invariants of every conceivable implementation.




                                    Although adding a default method to an existing interface facilitate backwards compatibility but the primary goal of adding this was to allow clients to ease use new interface without having to write their own implementation.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered yesterday









                                    Prabin PaudelPrabin Paudel

                                    1,39041528




                                    1,39041528



























                                        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

                                        How does Billy Russo acquire his 'Jigsaw' mask? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why does Bane wear the mask?Why does Kylo Ren wear a mask?Why did Captain America remove his mask while fighting Batroc the Leaper?How did the OA acquire her wisdom?Is Billy Breckenridge gay?How does Adrian Toomes hide his earnings from the IRS?What is the state of affairs on Nootka Sound by the end of season 1?How did Tia Dalma acquire Captain Barbossa's body?How is one “Deemed Worthy”, to acquire the Greatsword “Dawn”?How did Karen acquire the handgun?

                                        Личност Атрибути на личността | Литература и източници | НавигацияРаждането на личносттаредактиратередактирате

                                        A sequel to Domino's tragic life Why Christmas is for Friends Cold comfort at Charles' padSad farewell for Lady JanePS Most watched News videos