Thursday, 27 February 2014

Java Object Sorting Example (Comparable And Comparator)



In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value.

1. Sort an Array

To sort an Array, use the Arrays.sort().
 String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; 
 
 Arrays.sort(fruits);
 
 int i=0;
 for(String temp: fruits){
  System.out.println("fruits " + ++i + " : " + temp);
 }
Output
fruits 1 : Apple
fruits 2 : Banana
fruits 3 : Orange
fruits 4 : Pineapple

2. Sort an ArrayList

To sort an ArrayList, use the Collections.sort().
 List<String> fruits = new ArrayList<String>();
 
 fruits.add("Pineapple");
 fruits.add("Apple");
 fruits.add("Orange");
 fruits.add("Banana");
 
 Collections.sort(fruits);
 
 int i=0;
 for(String temp: fruits){
  System.out.println("fruits " + ++i + " : " + temp);
 }
Output
fruits 1 : Apple
fruits 2 : Banana
fruits 3 : Orange
fruits 4 : Pineapple

3. Sort an Object with Comparable

How about a Java Object? Let create a Fruit class:
public class Fruit{
 
 private String fruitName;
 private String fruitDesc;
 private int quantity;
 
 public Fruit(String fruitName, String fruitDesc, int quantity) {
  super();
  this.fruitName = fruitName;
  this.fruitDesc = fruitDesc;
  this.quantity = quantity;
 }
 
 public String getFruitName() {
  return fruitName;
 }
 public void setFruitName(String fruitName) {
  this.fruitName = fruitName;
 }
 public String getFruitDesc() {
  return fruitDesc;
 }
 public void setFruitDesc(String fruitDesc) {
  this.fruitDesc = fruitDesc;
 }
 public int getQuantity() {
  return quantity;
 }
 public void setQuantity(int quantity) {
  this.quantity = quantity;
 }
}
To sort it, you may think of Arrays.sort() again, see below example :
package com.naresh;
 
import java.util.Arrays;
 
public class SortFruitObject{
 
 public static void main(String args[]){
 
  Fruit[] fruits = new Fruit[4];
 
  Fruit pineappale = new Fruit("Pineapple", "Pineapple description",70); 
  Fruit apple = new Fruit("Apple", "Apple description",100); 
  Fruit orange = new Fruit("Orange", "Orange description",80); 
  Fruit banana = new Fruit("Banana", "Banana description",90); 
 
  fruits[0]=pineappale;
  fruits[1]=apple;
  fruits[2]=orange;
  fruits[3]=banana;
 
  Arrays.sort(fruits);
 
  int i=0;
  for(Fruit temp: fruits){
     System.out.println("fruits " + ++i + " : " + temp.getFruitName() + 
   ", Quantity : " + temp.getQuantity());
  }
 
 } 
}
Nice try, but, what you expect the Arrays.sort() will do? You didn’t even mention what to sort in the Fruit class. So, it will hits the following error :
Exception in thread "main" java.lang.ClassCastException: 
com.mkyong.common.Fruit cannot be cast to java.lang.Comparable
 at java.util.Arrays.mergeSort(Unknown Source)
 at java.util.Arrays.sort(Unknown Source)
To sort an Object by its property, you have to make the Object implement the Comparable interface and override thecompareTo() method. Lets see the new Fruit class again.
public class Fruit implements Comparable<Fruit>{
 
 private String fruitName;
 private String fruitDesc;
 private int quantity;
 
 public Fruit(String fruitName, String fruitDesc, int quantity) {
  super();
  this.fruitName = fruitName;
  this.fruitDesc = fruitDesc;
  this.quantity = quantity;
 }
 
 public String getFruitName() {
  return fruitName;
 }
 public void setFruitName(String fruitName) {
  this.fruitName = fruitName;
 }
 public String getFruitDesc() {
  return fruitDesc;
 }
 public void setFruitDesc(String fruitDesc) {
  this.fruitDesc = fruitDesc;
 }
 public int getQuantity() {
  return quantity;
 }
 public void setQuantity(int quantity) {
  this.quantity = quantity;
 }
 
 public int compareTo(Fruit compareFruit) {
 
  int compareQuantity = ((Fruit) compareFruit).getQuantity(); 
 
  //ascending order
  return this.quantity - compareQuantity;
 
  //descending order
  //return compareQuantity - this.quantity;
 
 } 
}
The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.
The compareTo() method is hard to explain, in integer sorting, just remember
  1. this.quantity – compareQuantity is ascending order.
  2. compareQuantity – this.quantity is descending order.
To understand more about compareTo() method, read this Comparable documentation.
Run it again, now the Fruits array is sort by its quantity in ascending order.
fruits 1 : Pineapple, Quantity : 70
fruits 2 : Orange, Quantity : 80
fruits 3 : Banana, Quantity : 90
fruits 4 : Apple, Quantity : 100

4. Sort an Object with Comparator

How about sorting with Fruit’s “fruitName” or “Quantity”? The Comparable interface is only allow to sort a single property. To sort with multiple properties, you need Comparator. See the new updated Fruit class again :
import java.util.Comparator;
 
public class Fruit implements Comparable<Fruit>{
 
 private String fruitName;
 private String fruitDesc;
 private int quantity;
 
 public Fruit(String fruitName, String fruitDesc, int quantity) {
  super();
  this.fruitName = fruitName;
  this.fruitDesc = fruitDesc;
  this.quantity = quantity;
 }
 
 public String getFruitName() {
  return fruitName;
 }
 public void setFruitName(String fruitName) {
  this.fruitName = fruitName;
 }
 public String getFruitDesc() {
  return fruitDesc;
 }
 public void setFruitDesc(String fruitDesc) {
  this.fruitDesc = fruitDesc;
 }
 public int getQuantity() {
  return quantity;
 }
 public void setQuantity(int quantity) {
  this.quantity = quantity;
 }
 
 public int compareTo(Fruit compareFruit) {
 
  int compareQuantity = ((Fruit) compareFruit).getQuantity(); 
 
  //ascending order
  return this.quantity - compareQuantity;
 
  //descending order
  //return compareQuantity - this.quantity;
 
 }
 
 public static Comparator<Fruit> FruitNameComparator 
                          = new Comparator<Fruit>() {
 
     public int compare(Fruit fruit1, Fruit fruit2) {
 
       String fruitName1 = fruit1.getFruitName().toUpperCase();
       String fruitName2 = fruit2.getFruitName().toUpperCase();
 
       //ascending order
       return fruitName1.compareTo(fruitName2);
 
       //descending order
       //return fruitName2.compareTo(fruitName1);
     }
 
 };
}
The Fruit class contains a static FruitNameComparator method to compare the “fruitName”. Now the Fruit object is able to sort with either “quantity” or “fruitName” property. Run it again.
1. Sort Fruit array based on its “fruitName” property in ascending order.
Arrays.sort(fruits, Fruit.FruitNameComparator);
Output
fruits 1 : Apple, Quantity : 100
fruits 2 : Banana, Quantity : 90
fruits 3 : Orange, Quantity : 80
fruits 4 : Pineapple, Quantity : 70
2. Sort Fruit array based on its “quantity” property in ascending order.
Arrays.sort(fruits)
Output
fruits 1 : Pineapple, Quantity : 70
fruits 2 : Orange, Quantity : 80
fruits 3 : Banana, Quantity : 90
fruits 4 : Apple, Quantity : 100
The java.lang.Comparable and java.util.Comparator are powerful but take time to understand and make use of it, may be it’s due to the lacking of detail example.

Sunday, 16 February 2014

How To Calculate Date And Time Difference In Java


How To Calculate Date And Time Difference In Java


In this tutorial, we show you 2 examples to calculate date / time difference in Java :
  1. Manual time calculation.
  2. Joda time library.

1. Manual time calculation

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :
1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
DateDifferentExample.java
package com.naresh.date;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateDifferentExample {
 
 public static void main(String[] args) {
 
  String dateStart = "02/14/2014 09:29:58";
  String dateStop = "02/15/2014 10:31:48";
 
  //HH converts hour in 24 hours format (0-23), day calculation
  SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
 
  Date d1 = null;
  Date d2 = null;
 
  try {
   d1 = format.parse(dateStart);
   d2 = format.parse(dateStop);
 
   //in milliseconds
   long diff = d2.getTime() - d1.getTime();
 
   long diffSeconds = diff / 1000 % 60;
   long diffMinutes = diff / (60 * 1000) % 60;
   long diffHours = diff / (60 * 60 * 1000) % 24;
   long diffDays = diff / (24 * 60 * 60 * 1000);
 
   System.out.print(diffDays + " days, ");
   System.out.print(diffHours + " hours, ");
   System.out.print(diffMinutes + " minutes, ");
   System.out.print(diffSeconds + " seconds.");
 
  } catch (Exception e) {
   e.printStackTrace();
  }
 
 }
 
}
Result
1 days, 1 hours, 1 minutes, 50 seconds.
Why seconds and minutes need %60, and hours %24?
If you change it to
long diffSeconds = diff / 1000;
The result will be
1 days, 1 hours, 1 minutes, 90110 seconds.
The “90110” is the total number of seconds difference between date1 and date2, this is correct if you want to know the differences in seconds ONLY.
To display difference in “day, hour, minute and second” format, you should use a modulus (%60) to cut off the remainder of seconds (90060). Got it? The idea is applied in minutes (%60) and hours (%24) as well.
90110 % 60 = 50 seconds (you want this)
90110 - 50 = 90060 seconds (you dont want this)

2. Joda Time Example

Here’s the equivalent example, but using Joda time to calculate differences between two dates.
P.S This example is using joda-time-2.1.jar
JodaDateDifferentExample.java
package com.naresh.date;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;
 
public class JodaDateDifferentExample {
 
  public static void main(String[] args) {
 
 String dateStart = "02/14/2014 09:29:58";
 String dateStop = "02/15/2014 10:31:48";
 
 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
 
 Date d1 = null;
 Date d2 = null;
 
 try {
  d1 = format.parse(dateStart);
  d2 = format.parse(dateStop);
 
  DateTime dt1 = new DateTime(d1);
  DateTime dt2 = new DateTime(d2);
 
  System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
  System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
  System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
  System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");
 
  } catch (Exception e) {
  e.printStackTrace();
  }
 
  }
 
}
Result
1 days, 1 hours, 1 minutes, 50 seconds.

Tuesday, 11 February 2014

Java Date And Calendar Examples



Java Date And Calendar Examples


This tutorial shows you how to work with java.util.Date and java.util.Calendar.

1. Java Date Examples

Few examples to work with Date APIs.
Example 1.1 – Convert Date to String.
 SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
 String date = sdf.format(new Date()); 
 System.out.println(date); //15/01/2014
Example 1.2 – Convert String to Date.
 SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
 String dateInString = "31-08-1982 10:20:56";
 Date date = sdf.parse(dateInString);
 System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982
P.S Refer to this – SimpleDateFormat JavaDoc for detail date and time patterns.
Example 1.3 – Get current date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date)); //2014/01/15 16:16:39

2. Java Calendar Example

Few examples to work with Calendar APIs.
Example 2.1 – Get current date time
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss"); 
 Calendar calendar = new GregorianCalendar(2014,0,31);
 System.out.println(sdf.format(calendar.getTime()));
Output
2014 Jan 31 00:00:00
Example 2.2 – Simple Calendar example
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss"); 
 Calendar calendar = new GregorianCalendar(2014,1,28,13,24,56);
 
 int year       = calendar.get(Calendar.YEAR);
 int month      = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
 int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); 
 int dayOfWeek  = calendar.get(Calendar.DAY_OF_WEEK);
 int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
 int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
 
 int hour       = calendar.get(Calendar.HOUR);        // 12 hour clock
 int hourOfDay  = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
 int minute     = calendar.get(Calendar.MINUTE);
 int second     = calendar.get(Calendar.SECOND);
 int millisecond= calendar.get(Calendar.MILLISECOND);
 
 System.out.println(sdf.format(calendar.getTime()));
 
 System.out.println("year \t\t: " + year);
 System.out.println("month \t\t: " + month);
 System.out.println("dayOfMonth \t: " + dayOfMonth);
 System.out.println("dayOfWeek \t: " + dayOfWeek);
 System.out.println("weekOfYear \t: " + weekOfYear);
 System.out.println("weekOfMonth \t: " + weekOfMonth);
 
 System.out.println("hour \t\t: " + hour);
 System.out.println("hourOfDay \t: " + hourOfDay);
 System.out.println("minute \t\t: " + minute);
 System.out.println("second \t\t: " + second);
 System.out.println("millisecond \t: " + millisecond);
Output
2014 Feb 28 13:24:56
year   : 2014
month   : 1
dayOfMonth  : 28
dayOfWeek  : 5
weekOfYear  : 9
weekOfMonth     : 5
hour   : 1
hourOfDay  : 13
minute   : 24
second   : 56
millisecond     : 0
Example 2.3 – Set a date manually.
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
 
 Calendar calendar = new GregorianCalendar(2014,1,28,13,24,56); 
 System.out.println("#1. " + sdf.format(calendar.getTime()));
 
 //update a date
 calendar.set(Calendar.YEAR, 2014);
 calendar.set(Calendar.MONTH, 11);
 calendar.set(Calendar.MINUTE, 33);
 
 System.out.println("#2. " + sdf.format(calendar.getTime()));
Output
#1. 2014 Feb 28 13:24:56
#2. 2014 Dec 28 13:33:56
Example 2.4- Add or subtract from a date.
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd"); 
 
 Calendar calendar = new GregorianCalendar(2014,10,28); 
 System.out.println("Date : " + sdf.format(calendar.getTime()));
 
 //add one month
 calendar.add(Calendar.MONTH, 1);
 System.out.println("Date : " + sdf.format(calendar.getTime()));
 
 //subtract 10 days
 calendar.add(Calendar.DAY_OF_MONTH, -10);
 System.out.println("Date : " + sdf.format(calendar.getTime()));
Output
Date : 2014 Nov 28
Date : 2014 Dec 28
Date : 2014 Dec 18

3. DateValidator example


package com.naresh.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateValidator {

      public boolean isThisDateValid(String dateToValidate, String dateFromat){
             
            if(dateToValidate == null){
                  return false;
            }

            SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
            sdf.setLenient(false);

            try {
                  //if not valid, it will throw ParseException
                  Date date = sdf.parse(dateToValidate);
                  System.out.println(date);

            } catch (ParseException e) {

                  e.printStackTrace();
                  return false;
            }

            return true;
      }

}