Comparator in Java8

Comparator is comparatively easy to use in Java8. Functional style of programming in Java8 has introduced new way to use the comparator.

This is what we we do before Java8. Kindly note that getDob() method returns date of birth of a Student, which is java.util.Date instance.

studentList.sort(new Comparator<Student>() {

     @Override
     public int compare(Student o1, Student o2) {
         return o1.getDob().compareTo(o2.getDob());
     }
});

Here we can see that we have to create the anonymous class of comparator and then we provide the sorting logic.  With Java8 we can use Lambada expression to reduce the extra boiler plate code of comparator declaration and compare method declaration.

studentList.sort((o1, o2) ->  {
    return o1.getDob().compareTo(o2.getDob());
});

You can see how it is reduced in size. Even more there are lot of default methods has been introduced in Comparator interface. For example,

studentList.sort(Comparator.comparing(Student::getDob));

Here comparing method will prepare the comparator based on the method reference we have provided. Moreover, we can also simply reverse the order of sorting,

studentList.sort(Comparator.comparing(Student::getDob).reversed());

Lot more default methods are there in Comparator interface to reduce the extra code of comparator declaration and speed up the development.

 

Hello Jar

.jar, the wrapped or archived Java application to be used or run on any system with required java run time (JRE). It should have main method, the entry point to start the execution of the application. You can create the jar file with the help of inbuilt Java Archive Tool which is provided in JDK. Continue reading “Hello Jar”

BubbleSort with Java

Bubble sort is one of the easiest algorithms. It simply uses iteration and swapping in it. In this algorithm smaller elements of the array or list  bubbles up to first that’s why it’s named as bubble sort.

Say we have array of {5, 4, 0, 3, 7}, than bubble sort takes first element Continue reading “BubbleSort with Java”

Default String representation of Object

I have seen many questions on StackOverFlow where users comes up with the output which contains some gibberish(at least they feel so) text like abc@195a09c. So, let’s see what this output actually means. Continue reading “Default String representation of Object”