In Java, if you want to sort a collection object or array object, you need to implement the comparator interface to achieve the goal that we want.
Next we simulate the sorting of the Date property in the collection object
First, the entity class step
Package com.ljq.entity;
/**
*/
public class step{
/** Time * *
Private String Accepttime = "";
/** Location * *
Private String acceptaddress = "";
Public Step () {
Super ();
}
Public Step (String accepttime, String acceptaddress) {
Super ();
This.accepttime = Accepttime;
this.acceptaddress = acceptaddress;
}
Public String Getaccepttime () {
return accepttime;
}
public void Setaccepttime (String accepttime) {
This.accepttime = Accepttime;
}
Public String getacceptaddress () {
return acceptaddress;
}
public void setacceptaddress (String acceptaddress) {
this.acceptaddress = acceptaddress;
}
}
Second, realize comparator interface
Package com.ljq.entity;
Import Java.util.Comparator;
Import Java.util.Date;
Import Com.ljq.util.UtilTool;
/**
* Sort the Step class
* @author Administrator
*
*/
public class Stepcomparator implements comparator<step>{
/**
* Returns a negative number if O1 is less than O2, returns a positive number if O1 is greater than O2, and returns 0 if they are equal;
*/
@Override
public int Compare (step O1, step O2) {
Date accepttime1=utiltool.strtodate (O1.getaccepttime (), NULL);
Date accepttime2=utiltool.strtodate (O2.getaccepttime (), NULL);
Ascending the Date field, if you want to use the Before method in descending order
if (Accepttime1.after (acceptTime2)) return 1;
return-1;
}
}
Third, testing
Package junit;
Import java.util.Collection;
Import java.util.Collections;
Import java.util.List;
Import Org.junit.Test;
public class Stepcomparatortest {
@Test
public void sort () throws exception{
List<step> steps=new arraylist<step>;
To sort a collection object
Stepcomparator comparator=new stepcomparator ();
Collections.sort (steps, comparator);
if (Steps!=null&&steps.size () >0) {
for (Step step:steps) {
System.out.println (Step.getacceptaddress ());
System.out.println (Step.getaccepttime ());
}
}
}
}
The use of comparator in Java--implementing collections and array ordering