Showing posts with label Lambda Expressions. Show all posts
Showing posts with label Lambda Expressions. Show all posts

Wednesday, August 14, 2019

Java 8: Method Reference

Method Reference is a shorthand notation of Lambda Expression.

For example, you want to add an ActionListener to a JButton actButton.

Before Java 8:

actButton.addActionListener(new ActionListener () {
      public void actionPerformed(ActionEvent e) {
            searchButton.requestFocusInWindow();
      }
});


Use Lambda Expression:

actButton.addActionListener((ActionEvent e) -> {
      searchButton.requestFocusInWindow();
});


Use Method Reference:

actButton.addActionListener(searchButton::requestFocusInWindow());

If the method you are referencing is a member of the current class, it is also known as Memeber Reference.

For example, you are working in a class that is a subclass of the JFrame. After you have done some modification of the GUI, you want to call the pack() method.

javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
            this.pack();
      }
}


Use Memeber Reference:

javax.swing.SwingUtilities.invokeLater(this::pack());

The method called in Method Reference can be ordinary instance member of a class as shown in our above examples, a static method of a class, or even a constructor of a class, as long as the signature of the method exactly matches the method in the functional interface.

To reference a static method:

javax.swing.SwingUtilities.invokeLater(ResultCalss::print());

It requires the signature of the method print() matches the signature of the run() method in the Runnable interface.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Reference:
Method References in Java 8


Friday, August 9, 2019

NetBeans: Migrate from an early JDK to Java 8 or a later version

After you have updated the Java platform from an earlier version to Java 8 or a later version, you want to convert the old java code to one with the new features of the newly added Java version.

Of course, you can check your code line by line to convert it manually. However, you can use the NetBeans built-in feature to perform this, which will save you a lot of time and effort.

1. Click the Refactor in the top menu of the NetBeans IDE, and choose Inspect and Transform/



2. In the Inspect and Transform window, select a project you want to refactor from the drop-down list next to the Inspect label.



3. While the Configuration is checked, select the target JDK you will convert to from the drop-down list next to the Configuration label. Then, click the Inspect button.



4. If the below window pops up, click the Inspect button again to continue.



5. In the Refactoring window, click the upward arrow with the notation "Previous Occurrence" on the left column of the window to view the suggestions of code changes.



6. Use the upward and downward arrows on the left column to view all the changes. If all look OK, click the Do Refactoring button.


-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Thursday, April 17, 2014

What is a functional interface? Features of functional interfaces

Functional Interface is a new concept introduced in java 8. Functional interfaces are particularly used for Lambda Expressions. Following are the characters of function interfaces.

1. A functional interface can have only one abstract method except those methods declared in the Object class. For example the Runable interface has only one method run(), therefore it is a functional interface. Following is another example.

     public interface Qualified {
            public Object getTheObject();
            public String toString();
            public boolean equals(Object obj);
      }
Since the toString and equals methods are methods declared in the Object class, this Qualified interface is also a functional interface.

2. A functional interface can have static and default methods.

      public interface GetIt {
            public Object getIt();

            public static boolean checkIt(Object obj) {
                  if (obj instanceof String) return true;
                  return false;
            }

            public default Integer getSum(Integer one, Integer two) {
                  return one+two;
            }
      }
The GetIt interface has only one abstract method, getIt, so it is a functional interface.

3. The abstract method of a functional interface can be inherited from another interface or overrides a method in another interface.

       //interface Face1 has two abstract methods
       interface Face1 {
          public boolean isTrue();
          public void changeIt();
      }

      //interface Face2 has one abstract method, changeIt, inherited from face1
      //therefore, interface Face2 is a functional interface
      interface Face2 extends Face1 {
          @Override
          default boolean isTrue() {return true;}
      }

      //interface Face3 has one abstract method that overrides the method in its super interface
      //therefore, interface Face3 is a functional interface
      interface Face3 extends Face2 {
            @Override
            public void changeIt();
      }

      //Since Face2 and Face3 are functional interfaces, they can be implemented with Lambda Expression
      public class TestDefautMethod {
            public void testDefault(Face2 theFace2, Face3 theFace3){
                  theFace2.changeIt();
                  theFace3.changeIt();
            }
 
            public static void main(String[] args){
                 TestDefautMethod tester = new TestDefautMethod();
                 tester.testDefault(()->System.out.println("Changed it successfully in Face2!"),
                                           ()->System.out.println("Changed it successfully in Face3!"));
           }
      }
The output of executing TestDefautMethod is the following.
      Changed it successfully in Face2!
      Changed it successfully in Face3!

4. In java 8, a functional interface is normally marked with the annotation @FunctionalInterface. However, as long as an interface has only one abstract method, it is a qualified functional interface regardless whether it has the annotation or not.

However, if an interface has the @FunctionalInterface annotation and contains more than one abstract method, the compiler will identify it as an error.

       @FunctionalInterface
       interface Face4 extends Face3 {
              public Integer sumIt(Integer one, Integer two);
       }
Face4 has two abstract methods, changeIt inherited from super interface and sumIt declared in itself. Compiling this code generates the following error.

error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
  Face4 is not a functional interface
    multiple non-overriding abstract methods found in interface Face4

References:

1. Default Methods

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, March 25, 2014

Lambda Expressions and functional interface in Java 8

Lambda Expression is a new feature added to Java 8. It simplifies code by passing functions/methods directly to a method as parameters. It is used for implementing interfaces that have only one abstract method, known as functional interfaces. Since the interface has only one abstract method, when a method from another object has an argument that is the type of this interface, a lambda expression can be used to put the implementation of the functional interface, the code for overriding the abstract method of the interface, in the place of the argument of the method.

The syntax of Lambda Expressions

1. A parenthesis within which has a comma-separated list of objects/primitives which are the parameters of the abstract method that this Lambda Expression is overriding. If there is only one item in the parenthesis, the parenthesis can be removed. If the abstract method takes no argument, the empty parenthesis "()" (without the quotes) is used.

2. The right headed arrow ( -> ) that separates the parameters from the method implementation.

3. The body that implements the logic of the method.

For example:
       (int a, int b) -> a > b && (a - b) < 50
can be the implementation of such a functional interface:
       public interface Calculator {
              public boolean test(int a, int b);
      }
If you have the following code that uses the Calculator as a parameter:
      public class DecisionMaker {
            public Person getThe RightPerson (Person person1,
                                                                Person person2,
                                                               Calculator calculator) {
                    int age1 = person1.getAge(), age2 =  person2.getAge();

                   if (calculator.test(age1, age2)) {
                         return person1;
                  } else {
                         return person2;
                  }
            }
      }
Since Calculator is an interface, before Java 8, you have to create a class to implement this interface before you can use it, and you pass an instance of the implementing class to the method. However, with Lambda Expression, the implementing class can be omitted.
   
Without using Lambda Expression:
       public class MyCalculator implements Calculator {
               public boolean test (int a, int b) {
                      System.out.println("Without using lambda expression."); 
                      return (a > b && (a - b) < 50);
               }
       }
     
       DecisionMaker dm = new DecisionMaker();
       Person rightPerson = dm.getTheRightPerson(
                                                person1,
                                                person2,
                                                new MyCalculator());

Using Lambda Expression:
       DecisionMaker dm = new DecisionMaker();
       Person rightPerson = dm.getTheRightPerson(
                                                person1,
                                                person2,
                                                (int a, int b) -> {System.out.println("Using lambda expression."); return a > b && (a - b) < 50;});

Another Example

Here is another example of using Lambda Expressions. Every year, in your company, you give a special prize to those employees whose performance is over 800 and whose team's performance is over 600. You can use the following code to get a list of those that qualify for the prize.

//Create the functional interface.
//A functional interface is an interface that contains only one abstract method.
//It may have one or more static and default methods.
public interface Qualifier {
      public boolean isQualified (Employee employee, Team team);
}

//The class that does the screening
public class SpecialPrizeScreener {
      public List<Employee> getSpecialPrizeWinners(List<Employee> allEmployees,
                                          List<Team> teams,
                                          Qualifier qualifier) {

            List<Employee> result = new ArrayList<Employee>();
         
            for (Employee employee : allEmployees){
                  for (Team team : teams) {
                         if (team.contains(employee)) {
                                if (qualifier.isQualified(employee, team) {
                                       result.add(employee);
                                }
                         }
                   }
   }
            return result;
      }

      public static void main(String[] args) {
            SpecialPrizeScreener screener = new SpecialPrizeScreener();
            List<Employee> allEmployees = <your method to get all your employees>;
            List<Team> teams = <your method to get all the teams>;

            //The method name can be omitted in Java 8 when implementing a functional interface.
            //Thus, the Lambda Expression can be used in implementing the functional interface
            //and used directly as a parameter of the method call.
            List<Employee> specialPrizeWinners = screener.getSpecialPrizeWinners (
                        allEmployees,
                        teams,
                        (Employee employee, Team team) -> employee.getPerformance() > 800
                                                        && team.getPerformance() > 600);

      }
}

Using generic functional interface

//Create the functional interface that takes generics
public interface Qualifier<K, V> {
      public boolean isQualified (K param1, V param2);
}

//Modify the getSpecialPrizeWinners method in the SpecialPrizeScreener class to let the Qualifier take Employee and Team as its generic types.

      public List<Employee> getSpecialPrizeWinners(List<Employee> allEmployees,
                                          List<Team> teams,
                                          Qulifier<Employee, Team> qualifier)

//In the above Lambda Expression, the parameter types can be omitted.
List<Employee> specialPrizeWinners = screener.getSpecialPrizeWinners (
                        allEmployees,
                        teams,
                        (employee, team) -> employee.getPerformance() > 800
                                                        && team.getPerformance() > 600);

Using multiple Lambda Expressions

//You may use as many as Lambda Expressions in a method wherever it is possible
//You may modify the above code to add another Lambda Expression.

//Using the functional interface Consumer<T> interface
public interface Consumer<T> {
      public void accept(T t);
}


public class SpecialPrizeScreener {
      public void getSpecialPrizeWinners(List<Employee> allEmployees,
                                          List<Team> teams,
                                          List<Employee> result,
                                          Qulifier qualifier,
                                          Consumer<Employee> consumer) {

            for (Employee employee : allEmployees){
                  for (Team team : teams) {
                         if (team.contains(employee)) {
                                if (qualifier.isQualified(employee, team) {
                                       consumer.accept(employee);
                                }
                         }
                   }
   }
      }

      public static void main(String[] args) {
            SpecialPrizeScreener screener = new SpecialPrizeScreener();
            List<Employee> allEmployees = <your method to get all your employees>;
            List<Team> teams = <your method to get all the teams>;
            List<Employee> result = new ArrayList<Employee>();

            //implementing the additional Lambda Expression
            screener.getSpecialPrizeWinners (
                        allEmployees,
                        teams,
                        result,
                        (employee, team) -> employee.getPerformance() > 800
                                                        && team.getPerformance() > 600,
                        employee -> result.add(employee));

      }
}

------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.