Real world example of using a functional interface in Java [closed]












4















I know a functional interface means you can have exactly/only 1 abstract method with more than 1 default method(s) but I am wondering how to relate to it with a real-world example/situation of using a functional interface in Java.



Could you give a valid situation/example?



Thanks in advance!










share|improve this question















closed as too broad by Szymon Stepniak, Andy Turner, Nicholas K, DaveyDaveDave, wscourge Jan 2 at 11:42


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.














  • 1





    Lambda are implementations of Functional interface...so either implicitly (by a compiler or at runtime) or explicitly (by code...assignment) they are going to be used. Practical example is a Predicate usage across code for filtering.

    – Amit
    Jan 2 at 10:41


















4















I know a functional interface means you can have exactly/only 1 abstract method with more than 1 default method(s) but I am wondering how to relate to it with a real-world example/situation of using a functional interface in Java.



Could you give a valid situation/example?



Thanks in advance!










share|improve this question















closed as too broad by Szymon Stepniak, Andy Turner, Nicholas K, DaveyDaveDave, wscourge Jan 2 at 11:42


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.














  • 1





    Lambda are implementations of Functional interface...so either implicitly (by a compiler or at runtime) or explicitly (by code...assignment) they are going to be used. Practical example is a Predicate usage across code for filtering.

    – Amit
    Jan 2 at 10:41
















4












4








4








I know a functional interface means you can have exactly/only 1 abstract method with more than 1 default method(s) but I am wondering how to relate to it with a real-world example/situation of using a functional interface in Java.



Could you give a valid situation/example?



Thanks in advance!










share|improve this question
















I know a functional interface means you can have exactly/only 1 abstract method with more than 1 default method(s) but I am wondering how to relate to it with a real-world example/situation of using a functional interface in Java.



Could you give a valid situation/example?



Thanks in advance!







java java-8 functional-interface






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 23:08









Boann

37.1k1290121




37.1k1290121










asked Jan 2 at 9:46









Arun KumarArun Kumar

2,69692655




2,69692655




closed as too broad by Szymon Stepniak, Andy Turner, Nicholas K, DaveyDaveDave, wscourge Jan 2 at 11:42


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.









closed as too broad by Szymon Stepniak, Andy Turner, Nicholas K, DaveyDaveDave, wscourge Jan 2 at 11:42


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.










  • 1





    Lambda are implementations of Functional interface...so either implicitly (by a compiler or at runtime) or explicitly (by code...assignment) they are going to be used. Practical example is a Predicate usage across code for filtering.

    – Amit
    Jan 2 at 10:41
















  • 1





    Lambda are implementations of Functional interface...so either implicitly (by a compiler or at runtime) or explicitly (by code...assignment) they are going to be used. Practical example is a Predicate usage across code for filtering.

    – Amit
    Jan 2 at 10:41










1




1





Lambda are implementations of Functional interface...so either implicitly (by a compiler or at runtime) or explicitly (by code...assignment) they are going to be used. Practical example is a Predicate usage across code for filtering.

– Amit
Jan 2 at 10:41







Lambda are implementations of Functional interface...so either implicitly (by a compiler or at runtime) or explicitly (by code...assignment) they are going to be used. Practical example is a Predicate usage across code for filtering.

– Amit
Jan 2 at 10:41














5 Answers
5






active

oldest

votes


















4














First of all annotation @FunctionalInterface is used by Java's built-in functional interfaces Predicate,Function,Consumer, etc...



From the other hand you may want to create your custom one like the following:



@FunctionalInterface
public interface ThrowingConsumer<T> {
void accept(T t) throws CustomException;
}


Then you can use it as a method parameter:



public <T, R> void doSomething(T value, ThrowingConsumer<T, R> consumer) {
// ...
}


And then call it like this:



doSomething(someValue, this::customConsumerMethodThrowingAnException);




It is worth to mention that @FunctionalInterface is not required. The compiler will be perfectly fine with any interface meeting the requirements.



The compiler treats it in a way similar to dealing with @Override annotation. The code compiles even without it. But once added it makes the code clearer and safer for the ones who will maintain the code in the future.






share|improve this answer


























  • Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

    – Boris the Spider
    Jan 2 at 11:17





















3














One of the primary use that they've provided is that the instances of functional interfaces can be created with lambda expressions and method references as well as using a constructor at the same time. For example, a functional interface Sample defined as:



@FunctionalInterface
public interface Sample {
void ab();
}


can be instantiated in as simple as a single line of code as :



Sample sample = () -> System.out.println("ab called");


and then called wherever required as:



sample.ab();




I would further quote the Javadoc from the java.util.function package:




Functional interfaces can provide a target type in multiple contexts,
such as assignment context, method invocation, or cast context:



 // Assignment context
Predicate<String> p = String::isEmpty;

// Method invocation context
stream.filter(e -> e.getSize() > 10)...

// Cast context
stream.map((ToIntFunction) e -> e.getSize())...





Furthermore, such interfaces could be annotated with @FunctionalInterface annotation.




This annotation is not a requirement for the compiler to recognize
an interface as a functional interface, but merely an aid to capture
design intent
and enlist the help of the compiler in identifying
accidental violations of design intent.




Also a worthy point for using the concepts with existing such interfaces,



the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.






share|improve this answer

































    2














    We've always had functional interfaces before JDK8 but no lambdas, method references etc.



    As of JDK8, they provide a target type for lambda expressions, method references and in turn, have better readability and more compact code.



    Example, prior to Java-8 if you wanted to provide some logic that will be executed each time a Button component is clicked you'd do:



     btn.setOnAction(new EventHandler<ActionEvent>() { 
    @Override
    public void handle(ActionEvent event) {
    System.out.println("Hello World!");
    }
    });


    This is bulky, hard to read and not compact enough. because EventHandler is by definition a functional interface i.e. it has a SAM as of jdk8 you can now do:



    btn.setOnAction(event -> System.out.println("Hello World!"));


    You only see the part of the code you care about i.e. the logic to be executed when the button is clicked.



    Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when:




    • passing a comparator to a sort method e.g. List.sort, Stream.sorted, Collections.sort etc.

    • passing a block of code to run a task in a separate thread


    etc...



    while keeping the code readable, compact and concise.



    Functional interfaces are used extensively in the Java-stream API.



    There's no reason for you to create your own functional interface except there's not one that meets your requirements from java.util.function or the name of the functional interface is not as readable so thus you may create your own.





    There's also a @FunctionalInterface annotation recommended to be used but not required whenever you're creating a functional interface (the standard library uses this a lot).



    This enables the compiler to check that the annotated entity is an interface with a single abstract method otherwise gives an error.



    This is also quite helpful in being able to catch errors when refactoring your code.






    share|improve this answer

































      1














      Interfaces which are marked with FunctionalInterface are guaranteed to be applicable in contexts where a lambda expression with appropriate parameter and return types is expected. Besides that, they have no usage. There might be some optimizations, but in all cases it doesnt matter






      share|improve this answer































        1














        Lambdas are implementations of Functional interface...so either implicitly (by a compiler or at run-time) or explicitly (by code...assignment) they are going to be used. Practical example is




        1. Predicate : usage across code for filtering.

        2. Functions : Map.computeIfAbsent("xxx", s -> s.length());

        3. BiFunction : salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);

        4. Consumers : List.forEach(name -> System.out.println("Hello, " + name));






        share|improve this answer
































          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          First of all annotation @FunctionalInterface is used by Java's built-in functional interfaces Predicate,Function,Consumer, etc...



          From the other hand you may want to create your custom one like the following:



          @FunctionalInterface
          public interface ThrowingConsumer<T> {
          void accept(T t) throws CustomException;
          }


          Then you can use it as a method parameter:



          public <T, R> void doSomething(T value, ThrowingConsumer<T, R> consumer) {
          // ...
          }


          And then call it like this:



          doSomething(someValue, this::customConsumerMethodThrowingAnException);




          It is worth to mention that @FunctionalInterface is not required. The compiler will be perfectly fine with any interface meeting the requirements.



          The compiler treats it in a way similar to dealing with @Override annotation. The code compiles even without it. But once added it makes the code clearer and safer for the ones who will maintain the code in the future.






          share|improve this answer


























          • Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

            – Boris the Spider
            Jan 2 at 11:17


















          4














          First of all annotation @FunctionalInterface is used by Java's built-in functional interfaces Predicate,Function,Consumer, etc...



          From the other hand you may want to create your custom one like the following:



          @FunctionalInterface
          public interface ThrowingConsumer<T> {
          void accept(T t) throws CustomException;
          }


          Then you can use it as a method parameter:



          public <T, R> void doSomething(T value, ThrowingConsumer<T, R> consumer) {
          // ...
          }


          And then call it like this:



          doSomething(someValue, this::customConsumerMethodThrowingAnException);




          It is worth to mention that @FunctionalInterface is not required. The compiler will be perfectly fine with any interface meeting the requirements.



          The compiler treats it in a way similar to dealing with @Override annotation. The code compiles even without it. But once added it makes the code clearer and safer for the ones who will maintain the code in the future.






          share|improve this answer


























          • Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

            – Boris the Spider
            Jan 2 at 11:17
















          4












          4








          4







          First of all annotation @FunctionalInterface is used by Java's built-in functional interfaces Predicate,Function,Consumer, etc...



          From the other hand you may want to create your custom one like the following:



          @FunctionalInterface
          public interface ThrowingConsumer<T> {
          void accept(T t) throws CustomException;
          }


          Then you can use it as a method parameter:



          public <T, R> void doSomething(T value, ThrowingConsumer<T, R> consumer) {
          // ...
          }


          And then call it like this:



          doSomething(someValue, this::customConsumerMethodThrowingAnException);




          It is worth to mention that @FunctionalInterface is not required. The compiler will be perfectly fine with any interface meeting the requirements.



          The compiler treats it in a way similar to dealing with @Override annotation. The code compiles even without it. But once added it makes the code clearer and safer for the ones who will maintain the code in the future.






          share|improve this answer















          First of all annotation @FunctionalInterface is used by Java's built-in functional interfaces Predicate,Function,Consumer, etc...



          From the other hand you may want to create your custom one like the following:



          @FunctionalInterface
          public interface ThrowingConsumer<T> {
          void accept(T t) throws CustomException;
          }


          Then you can use it as a method parameter:



          public <T, R> void doSomething(T value, ThrowingConsumer<T, R> consumer) {
          // ...
          }


          And then call it like this:



          doSomething(someValue, this::customConsumerMethodThrowingAnException);




          It is worth to mention that @FunctionalInterface is not required. The compiler will be perfectly fine with any interface meeting the requirements.



          The compiler treats it in a way similar to dealing with @Override annotation. The code compiles even without it. But once added it makes the code clearer and safer for the ones who will maintain the code in the future.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 2 at 12:34

























          answered Jan 2 at 10:04









          ETOETO

          2,6281628




          2,6281628













          • Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

            – Boris the Spider
            Jan 2 at 11:17





















          • Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

            – Boris the Spider
            Jan 2 at 11:17



















          Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

          – Boris the Spider
          Jan 2 at 11:17







          Could you add a comment about @FunctionalInterface not being neccessary, but only being present to prevent SMIs used a lambdas from having methods added thus breaking interface compatibility. Otherwise this answer is about SMIs only - not @FunctionalInterface...

          – Boris the Spider
          Jan 2 at 11:17















          3














          One of the primary use that they've provided is that the instances of functional interfaces can be created with lambda expressions and method references as well as using a constructor at the same time. For example, a functional interface Sample defined as:



          @FunctionalInterface
          public interface Sample {
          void ab();
          }


          can be instantiated in as simple as a single line of code as :



          Sample sample = () -> System.out.println("ab called");


          and then called wherever required as:



          sample.ab();




          I would further quote the Javadoc from the java.util.function package:




          Functional interfaces can provide a target type in multiple contexts,
          such as assignment context, method invocation, or cast context:



           // Assignment context
          Predicate<String> p = String::isEmpty;

          // Method invocation context
          stream.filter(e -> e.getSize() > 10)...

          // Cast context
          stream.map((ToIntFunction) e -> e.getSize())...





          Furthermore, such interfaces could be annotated with @FunctionalInterface annotation.




          This annotation is not a requirement for the compiler to recognize
          an interface as a functional interface, but merely an aid to capture
          design intent
          and enlist the help of the compiler in identifying
          accidental violations of design intent.




          Also a worthy point for using the concepts with existing such interfaces,



          the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.






          share|improve this answer






























            3














            One of the primary use that they've provided is that the instances of functional interfaces can be created with lambda expressions and method references as well as using a constructor at the same time. For example, a functional interface Sample defined as:



            @FunctionalInterface
            public interface Sample {
            void ab();
            }


            can be instantiated in as simple as a single line of code as :



            Sample sample = () -> System.out.println("ab called");


            and then called wherever required as:



            sample.ab();




            I would further quote the Javadoc from the java.util.function package:




            Functional interfaces can provide a target type in multiple contexts,
            such as assignment context, method invocation, or cast context:



             // Assignment context
            Predicate<String> p = String::isEmpty;

            // Method invocation context
            stream.filter(e -> e.getSize() > 10)...

            // Cast context
            stream.map((ToIntFunction) e -> e.getSize())...





            Furthermore, such interfaces could be annotated with @FunctionalInterface annotation.




            This annotation is not a requirement for the compiler to recognize
            an interface as a functional interface, but merely an aid to capture
            design intent
            and enlist the help of the compiler in identifying
            accidental violations of design intent.




            Also a worthy point for using the concepts with existing such interfaces,



            the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.






            share|improve this answer




























              3












              3








              3







              One of the primary use that they've provided is that the instances of functional interfaces can be created with lambda expressions and method references as well as using a constructor at the same time. For example, a functional interface Sample defined as:



              @FunctionalInterface
              public interface Sample {
              void ab();
              }


              can be instantiated in as simple as a single line of code as :



              Sample sample = () -> System.out.println("ab called");


              and then called wherever required as:



              sample.ab();




              I would further quote the Javadoc from the java.util.function package:




              Functional interfaces can provide a target type in multiple contexts,
              such as assignment context, method invocation, or cast context:



               // Assignment context
              Predicate<String> p = String::isEmpty;

              // Method invocation context
              stream.filter(e -> e.getSize() > 10)...

              // Cast context
              stream.map((ToIntFunction) e -> e.getSize())...





              Furthermore, such interfaces could be annotated with @FunctionalInterface annotation.




              This annotation is not a requirement for the compiler to recognize
              an interface as a functional interface, but merely an aid to capture
              design intent
              and enlist the help of the compiler in identifying
              accidental violations of design intent.




              Also a worthy point for using the concepts with existing such interfaces,



              the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.






              share|improve this answer















              One of the primary use that they've provided is that the instances of functional interfaces can be created with lambda expressions and method references as well as using a constructor at the same time. For example, a functional interface Sample defined as:



              @FunctionalInterface
              public interface Sample {
              void ab();
              }


              can be instantiated in as simple as a single line of code as :



              Sample sample = () -> System.out.println("ab called");


              and then called wherever required as:



              sample.ab();




              I would further quote the Javadoc from the java.util.function package:




              Functional interfaces can provide a target type in multiple contexts,
              such as assignment context, method invocation, or cast context:



               // Assignment context
              Predicate<String> p = String::isEmpty;

              // Method invocation context
              stream.filter(e -> e.getSize() > 10)...

              // Cast context
              stream.map((ToIntFunction) e -> e.getSize())...





              Furthermore, such interfaces could be annotated with @FunctionalInterface annotation.




              This annotation is not a requirement for the compiler to recognize
              an interface as a functional interface, but merely an aid to capture
              design intent
              and enlist the help of the compiler in identifying
              accidental violations of design intent.




              Also a worthy point for using the concepts with existing such interfaces,



              the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 2 at 11:38

























              answered Jan 2 at 9:59









              nullpointernullpointer

              43.5k10101201




              43.5k10101201























                  2














                  We've always had functional interfaces before JDK8 but no lambdas, method references etc.



                  As of JDK8, they provide a target type for lambda expressions, method references and in turn, have better readability and more compact code.



                  Example, prior to Java-8 if you wanted to provide some logic that will be executed each time a Button component is clicked you'd do:



                   btn.setOnAction(new EventHandler<ActionEvent>() { 
                  @Override
                  public void handle(ActionEvent event) {
                  System.out.println("Hello World!");
                  }
                  });


                  This is bulky, hard to read and not compact enough. because EventHandler is by definition a functional interface i.e. it has a SAM as of jdk8 you can now do:



                  btn.setOnAction(event -> System.out.println("Hello World!"));


                  You only see the part of the code you care about i.e. the logic to be executed when the button is clicked.



                  Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when:




                  • passing a comparator to a sort method e.g. List.sort, Stream.sorted, Collections.sort etc.

                  • passing a block of code to run a task in a separate thread


                  etc...



                  while keeping the code readable, compact and concise.



                  Functional interfaces are used extensively in the Java-stream API.



                  There's no reason for you to create your own functional interface except there's not one that meets your requirements from java.util.function or the name of the functional interface is not as readable so thus you may create your own.





                  There's also a @FunctionalInterface annotation recommended to be used but not required whenever you're creating a functional interface (the standard library uses this a lot).



                  This enables the compiler to check that the annotated entity is an interface with a single abstract method otherwise gives an error.



                  This is also quite helpful in being able to catch errors when refactoring your code.






                  share|improve this answer






























                    2














                    We've always had functional interfaces before JDK8 but no lambdas, method references etc.



                    As of JDK8, they provide a target type for lambda expressions, method references and in turn, have better readability and more compact code.



                    Example, prior to Java-8 if you wanted to provide some logic that will be executed each time a Button component is clicked you'd do:



                     btn.setOnAction(new EventHandler<ActionEvent>() { 
                    @Override
                    public void handle(ActionEvent event) {
                    System.out.println("Hello World!");
                    }
                    });


                    This is bulky, hard to read and not compact enough. because EventHandler is by definition a functional interface i.e. it has a SAM as of jdk8 you can now do:



                    btn.setOnAction(event -> System.out.println("Hello World!"));


                    You only see the part of the code you care about i.e. the logic to be executed when the button is clicked.



                    Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when:




                    • passing a comparator to a sort method e.g. List.sort, Stream.sorted, Collections.sort etc.

                    • passing a block of code to run a task in a separate thread


                    etc...



                    while keeping the code readable, compact and concise.



                    Functional interfaces are used extensively in the Java-stream API.



                    There's no reason for you to create your own functional interface except there's not one that meets your requirements from java.util.function or the name of the functional interface is not as readable so thus you may create your own.





                    There's also a @FunctionalInterface annotation recommended to be used but not required whenever you're creating a functional interface (the standard library uses this a lot).



                    This enables the compiler to check that the annotated entity is an interface with a single abstract method otherwise gives an error.



                    This is also quite helpful in being able to catch errors when refactoring your code.






                    share|improve this answer




























                      2












                      2








                      2







                      We've always had functional interfaces before JDK8 but no lambdas, method references etc.



                      As of JDK8, they provide a target type for lambda expressions, method references and in turn, have better readability and more compact code.



                      Example, prior to Java-8 if you wanted to provide some logic that will be executed each time a Button component is clicked you'd do:



                       btn.setOnAction(new EventHandler<ActionEvent>() { 
                      @Override
                      public void handle(ActionEvent event) {
                      System.out.println("Hello World!");
                      }
                      });


                      This is bulky, hard to read and not compact enough. because EventHandler is by definition a functional interface i.e. it has a SAM as of jdk8 you can now do:



                      btn.setOnAction(event -> System.out.println("Hello World!"));


                      You only see the part of the code you care about i.e. the logic to be executed when the button is clicked.



                      Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when:




                      • passing a comparator to a sort method e.g. List.sort, Stream.sorted, Collections.sort etc.

                      • passing a block of code to run a task in a separate thread


                      etc...



                      while keeping the code readable, compact and concise.



                      Functional interfaces are used extensively in the Java-stream API.



                      There's no reason for you to create your own functional interface except there's not one that meets your requirements from java.util.function or the name of the functional interface is not as readable so thus you may create your own.





                      There's also a @FunctionalInterface annotation recommended to be used but not required whenever you're creating a functional interface (the standard library uses this a lot).



                      This enables the compiler to check that the annotated entity is an interface with a single abstract method otherwise gives an error.



                      This is also quite helpful in being able to catch errors when refactoring your code.






                      share|improve this answer















                      We've always had functional interfaces before JDK8 but no lambdas, method references etc.



                      As of JDK8, they provide a target type for lambda expressions, method references and in turn, have better readability and more compact code.



                      Example, prior to Java-8 if you wanted to provide some logic that will be executed each time a Button component is clicked you'd do:



                       btn.setOnAction(new EventHandler<ActionEvent>() { 
                      @Override
                      public void handle(ActionEvent event) {
                      System.out.println("Hello World!");
                      }
                      });


                      This is bulky, hard to read and not compact enough. because EventHandler is by definition a functional interface i.e. it has a SAM as of jdk8 you can now do:



                      btn.setOnAction(event -> System.out.println("Hello World!"));


                      You only see the part of the code you care about i.e. the logic to be executed when the button is clicked.



                      Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when:




                      • passing a comparator to a sort method e.g. List.sort, Stream.sorted, Collections.sort etc.

                      • passing a block of code to run a task in a separate thread


                      etc...



                      while keeping the code readable, compact and concise.



                      Functional interfaces are used extensively in the Java-stream API.



                      There's no reason for you to create your own functional interface except there's not one that meets your requirements from java.util.function or the name of the functional interface is not as readable so thus you may create your own.





                      There's also a @FunctionalInterface annotation recommended to be used but not required whenever you're creating a functional interface (the standard library uses this a lot).



                      This enables the compiler to check that the annotated entity is an interface with a single abstract method otherwise gives an error.



                      This is also quite helpful in being able to catch errors when refactoring your code.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 2 at 11:24

























                      answered Jan 2 at 10:41









                      AomineAomine

                      42.3k74473




                      42.3k74473























                          1














                          Interfaces which are marked with FunctionalInterface are guaranteed to be applicable in contexts where a lambda expression with appropriate parameter and return types is expected. Besides that, they have no usage. There might be some optimizations, but in all cases it doesnt matter






                          share|improve this answer




























                            1














                            Interfaces which are marked with FunctionalInterface are guaranteed to be applicable in contexts where a lambda expression with appropriate parameter and return types is expected. Besides that, they have no usage. There might be some optimizations, but in all cases it doesnt matter






                            share|improve this answer


























                              1












                              1








                              1







                              Interfaces which are marked with FunctionalInterface are guaranteed to be applicable in contexts where a lambda expression with appropriate parameter and return types is expected. Besides that, they have no usage. There might be some optimizations, but in all cases it doesnt matter






                              share|improve this answer













                              Interfaces which are marked with FunctionalInterface are guaranteed to be applicable in contexts where a lambda expression with appropriate parameter and return types is expected. Besides that, they have no usage. There might be some optimizations, but in all cases it doesnt matter







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 2 at 9:52









                              NEGR KITAECNEGR KITAEC

                              1157




                              1157























                                  1














                                  Lambdas are implementations of Functional interface...so either implicitly (by a compiler or at run-time) or explicitly (by code...assignment) they are going to be used. Practical example is




                                  1. Predicate : usage across code for filtering.

                                  2. Functions : Map.computeIfAbsent("xxx", s -> s.length());

                                  3. BiFunction : salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);

                                  4. Consumers : List.forEach(name -> System.out.println("Hello, " + name));






                                  share|improve this answer






























                                    1














                                    Lambdas are implementations of Functional interface...so either implicitly (by a compiler or at run-time) or explicitly (by code...assignment) they are going to be used. Practical example is




                                    1. Predicate : usage across code for filtering.

                                    2. Functions : Map.computeIfAbsent("xxx", s -> s.length());

                                    3. BiFunction : salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);

                                    4. Consumers : List.forEach(name -> System.out.println("Hello, " + name));






                                    share|improve this answer




























                                      1












                                      1








                                      1







                                      Lambdas are implementations of Functional interface...so either implicitly (by a compiler or at run-time) or explicitly (by code...assignment) they are going to be used. Practical example is




                                      1. Predicate : usage across code for filtering.

                                      2. Functions : Map.computeIfAbsent("xxx", s -> s.length());

                                      3. BiFunction : salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);

                                      4. Consumers : List.forEach(name -> System.out.println("Hello, " + name));






                                      share|improve this answer















                                      Lambdas are implementations of Functional interface...so either implicitly (by a compiler or at run-time) or explicitly (by code...assignment) they are going to be used. Practical example is




                                      1. Predicate : usage across code for filtering.

                                      2. Functions : Map.computeIfAbsent("xxx", s -> s.length());

                                      3. BiFunction : salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);

                                      4. Consumers : List.forEach(name -> System.out.println("Hello, " + name));







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 2 at 10:48

























                                      answered Jan 2 at 10:43









                                      AmitAmit

                                      477113




                                      477113















                                          Popular posts from this blog

                                          Bressuire

                                          Cabo Verde

                                          Gyllenstierna