Wednesday, 1 November 2017

Comparable vs. Comparator in JAVA

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.


In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.



Monday, 18 September 2017

Lambda Expression : Replacement of Anonymous Inner Class

Lambda Expression:
·       A new feature of java8s
·       Main intension is replacement of anonymous inner class.
·       Lambda expression is nothing but an anonymous method(method without name)

The general form is :
(para-list)->
{
   //method body

};

Let's see an example for better clarity using normal interface approach, then using anonymous inner class approach, then lambda expression approach:

Approach-1:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}

class A implements Transaction
{
   public void withDraw(int amt)
   {
       System.out.println("amount withdrawn is"+amt);
   }
}
public class LambdaExpressionExample {

   public static void main(String[] args) {
      
       A ob1=new A();  
      
       ob1.withDraw(15000);
      
   }

}

Approach-2:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}



public class LambdaExpressionExample {

   public static void main(String[] args) {
      
       Transaction ob1=new Transaction()   //Anonymous Inner Class
       {
          public void withDraw(int amt)
          {
              System.out.println("amount withdrawn is"+amt);
          }
       };
      
       ob1.withDraw(15000);
      
   }

}

Approach-3:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}
public class LambdaExpressionExample {

   public static void main(String[] args) {
       Transaction ob1=(int amt)->
          {
              System.out.println("amount withdrawn is"+amt);
          };
ob1.withDraw(1500);
       

   }

}

Output:
amount withdrawn is1500

Sorting Collections with Java Lambdas

In Java, the Comparator class is used for sorting collections. In the following examples, we will sort a list of players based on name, surname, name length and last name letter. We will first sort them as we did before, using anonymous inner classes, and then reduce our code using lambda expressions.
In the first example, we will sort our list by name. Using the old way, this looks like this:

String[] players = {"Avijit", "Chintu", "Akshay", "Santosh", "Ritesh", "Avisek", "Krushna", "Surya", "Rudra", "Biswajit"};
 
// Sort players by name using anonymous innerclass
Arrays.sort(players, new Comparator<String>() {
       @Override
       public int compare(String s1, String s2) {
              return (s1.compareTo(s2));
       }
});
 
With lambdas, the same thing can be achieved like this:
// Sort players by name using lambda expression
Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));
 
Arrays.sort(players, sortByName);
// or this
Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));

Wednesday, 30 August 2017

Java - Why are interface variables static and final by default?

Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

public: for the accessibility across all the classes, just like the methods present in the interface

static: as interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it.

final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.
Also all these modifiers are implicit for an interface, you dont really need to specify any of them.

Can we define variables in interface in Java?

In Java , interface doesn't allow you to declare any instance variables. Using a variable declared in an interface as an instance variable will return a compile time error. You can declare a constant variable, using static final which is different from an instance variable.

Saturday, 19 August 2017

How Java Lambdas Expressions affect the code in simple way

Let us start with some basic examples. Here, we will see how lambda expressions affect the code in a simple way. Having a list of players, the “for loop”, as programmers often refers to the for statement, can be translated in Java SE 8 as below:

String[] s1 = {"Anant", "Nilan", "Dolagobinda", "Babu", "Rupeli", "Sanjay", "Akshay", "Santosh"};
List<String> players =  Arrays.asList(s1);
      
// Old looping
for (String player : players) {
     System.out.print(player + "; ");
}
      

// Using lambda expression and functional operations
players.forEach((player) -> System.out.print(player + "; "));

// Using double colon operator in Java 8
players.forEach(System.out::println);

What is JAVA Lambda Expression???

Java Lambda expressions are a new and important feature included in Java SE 8. A lambda expression provides a way to represent one method interface using an expression. A lambda expression is like a method, it provides a list of formal parameters and a body (which can be an expression or a block of code) expressed in terms of those parameters.

Lambda expressions also improve the Collection libraries. Java SE 8 added two packages related to bulk data operations for Collections, the java.util.function package, and the java.util.stream. A stream is like an iterator, but with a lot of extra functionality. Taken together, lambda expressions and streams are the biggest change to Java programming since the generics and annotations were added to the language.