Sunday, 6 April 2014

Sorting in List using Comparator and Comparable

You must have been came across the situation where you have to sort a collection of objects by a certain rule. And if you are working on a domain where people are your main entities, you will encounter it more. There must be many ways to it, which ranges from sorting on client UI using javascript to sorting on server side using complex algorithm, and sometimes in database too.
If you do not have millions of records to play with at a time then for sorting i will recommend you to consider comparable or comparator interface.
1. Comparable
Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo(). Here is an example to show the usage:
package com.skc.compare;

public class StudentCompare implements Comparable<StudentCompare> {

 private int studentId;
 private String studentName;
 private String studentStd;

 public StudentCompare(int studentId, String studentName, String studentStd) {
  super();
  this.studentId = studentId;
  this.studentName = studentName;
  this.studentStd = studentStd;
 }

 public int getStudentId() {
  return studentId;
 }

 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }

 public String getStudentName() {
  return studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

 public String getStudentStd() {
  return studentStd;
 }

 public void setStudentStd(String studentStd) {
  this.studentStd = studentStd;
 }

 @Override
 public String toString() {
  return "Student Id :" + this.getStudentId() + " Student Name : "
    + this.getStudentName() + " Student Standard : "
    + this.getStudentStd();
 }

 @Override
 public int compareTo(StudentCompare skc) {
  // TODO Auto-generated method stub
  return this.getStudentId() < skc.getStudentId() ? -1 : (this
    .getStudentId() > skc.getStudentId() ? 1 : 0);
 }

}
package com.skc.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentCompareDemo {
 public static void main(String[] args) {
  List<StudentCompare> studentList = new ArrayList<StudentCompare>();
  studentList.add(new StudentCompare(10,"SKC","B.Tech"));
  studentList.add(new StudentCompare(20,"SKC1","M.Tech"));
  studentList.add(new StudentCompare(11,"SKC2","B.Tech"));
  studentList.add(new StudentCompare(9,"SKC3","M.Tech"));
  studentList.add(new StudentCompare(26,"SKC4","MS"));
  studentList.add(new StudentCompare(1,"SKC5","BS"));
  for (StudentCompare skc:studentList) {
   System.out.println(skc);
  }
  System.out.println("After Sort");
  Collections.sort(studentList);
  for (StudentCompare skc:studentList) {
   System.out.println(skc);
  }
 }
}
Here, We can able to compare to a single field of a Class and We can able to sort in this way.If We have requirement to sort with any property, then we'll go for Comparator.

2. Comparator
Comparator is capable if comparing objects based on different attributes. e.g. 2 men can be compared based on `name` or `age` etc. (this can not be done using comparable. )
The method required to implement is compare(). Now let’s use another way to compare those TV by size. The common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.

package com.skc.compare;

public class Student {

 private int studentId;
 private String studentName;
 private String studentStd;

 public Student(int studentId, String studentName, String studentStd) {
  super();
  this.studentId = studentId;
  this.studentName = studentName;
  this.studentStd = studentStd;
 }

 public int getStudentId() {
  return studentId;
 }

 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }

 public String getStudentName() {
  return studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

 public String getStudentStd() {
  return studentStd;
 }

 public void setStudentStd(String studentStd) {
  this.studentStd = studentStd;
 }

 @Override
 public String toString() {
  return "Student Id :" + this.getStudentId() + " Student Name : "
    + this.getStudentName() + " Student Standard : "
    + this.getStudentStd();
 }

}

package com.skc.compare;

import java.util.Comparator;

public class StudentNameComparator implements Comparator<Student> {

 @Override
 public int compare(Student stud1, Student stud2) {
  // TODO Auto-generated method stub
  return stud1.getStudentStd().compareTo(stud2.getStudentStd());
 }

}

package com.skc.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class StudentComparatorDemo {
 public static void main(String[] args) {
  List<Student> studentList = new ArrayList<Student>();
  studentList.add(new Student(13,"SKCA","A"));
  studentList.add(new Student(11,"SKCB","B"));
  studentList.add(new Student(15,"SKCC","C"));
  studentList.add(new Student(10,"SKCD","D"));
  studentList.add(new Student(12,"SKCE","E"));
  studentList.add(new Student(14,"SKCF","F"));
 
  Collections.sort(studentList, new StudentNameComparator());
  for(Student student : studentList){  System.out.println(student.getStudentId()+"\t"+student.getStudentName()+"\t"+student.getStudentStd());
  }
 }
}
I will recommend all to use Comparator Interface to implements the Sorting in List as we can sort by the help of any property by creating an Object of that class. If we'll use Comparable over there , It is something Hard-Coded.

Difference between Comparator and Comparable :
Parameter
Comparable
Comparator
Sorting logic
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
Implementation

Class whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by id
Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id
Sorting method
int compareTo(Object o1)
This method compares this object with o1 object and returns  a integer.Its value has following meaning
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
int compare(Object o1,Object o2)
This method compares o1 and o2 objects. and returns  a integer.Its value has following meaning.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling method
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Package
Java.lang.Comparable
Java.util.Comparator

Saturday, 5 April 2014

Date Formating and Parsing in Java

Parsing of Date from one format to another format is one of the precious thing. In Java, We can able to parse  dates from strings, and format dates to strings, using a Helper Class of java.text package and that is java.text.SimpleDateFormat class.

Some Important Notation of Date Formating and  Parsing:
y   = year   (yy or yyyy)
M   = month  (MM)
d   = day in month (dd)
h   = hour (0-12)  (hh)
H   = hour (0-23)  (HH)
m   = minute in hour (mm)
s   = seconds (ss)
S   = milliseconds (SSS)
z   = time zone  text        (e.g. Pacific Standard Time...)
Z   = time zone, time offset (e.g. -0800)
Some Important Date Pattern that we need to achieve as per our requirement.
yyyy-MM-dd           (2009-12-31)

dd-MM-YYYY           (31-12-2009)
    
yyyy-MM-dd HH:mm:ss  (2009-12-31 23:59:59)

HH:mm:ss.SSS         (23:59.59.999)

yyyy-MM-dd HH:mm:ss.SSS   (2009-12-31 23:59:59.999)

yyyy-MM-dd HH:mm:ss.SSS Z   (2009-12-31 23:59:59.999 +0100)   

Code How can we format the Date Pattern into another Date Pattern:
Simple Code to Format the Date into other Pattern : 

  SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
   System.out.println(sdf1.format(new Date()));//06-04-2014
     
   SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
   System.out.println(sdf2.format(new Date()));//06-Apr-2014
    
   SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
   System.out.println(sdf3.format(new Date()));//2014-04-06
      
   SimpleDateFormat sdf4 =
                    new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
   System.out.println(sdf4.format(new Date()));
                     //2014-04-06 11:48:36
      
  SimpleDateFormat sdf5 =
               new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS z");
  System.out.println(sdf5.format(new Date()));
                 //2014-04-06 11:49:58:775 IST
    
  SimpleDateFormat sdf6 =
             new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS z Z");
  System.out.println(sdf6.format(new Date()));
              //2014-04-06 11:50:39:297 IST +0530

Simple Code to parse the Date into other Pattern : 

          
  SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd");
   try {
    //Input is : 1991-03-24
    System.out.println(sdf5.parseObject(new Scanner(System.in).next()));
//Sun Mar 24 00:00:00 IST 1991
   } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
Convert java.util.Date to java.sql.Date and  java.sql.Date to java.util.Date : 

java.sql.Date to java.util.Date

 java.sql.Date sd = new java.sql.Date(System.currentTimeMillis());
 java.util.Date ud = new java.util.Date(sd.getTime());
 System.out.println(sd);//2014-04-06

java.util.Date to java.sql.Date:

  java.util.Date ud = new java.util.Date();
  java.sql.Date sd = new java.sql.Date(ud.getTime());
  System.out.println(sd);//2014-04-06

Like that , so many third party utility classes are there where we can convert one pattern to another.My request to all of you, while implementing the third party utility class please make a POC and test it in every aspect.

Thanks