Program to Sort list of month (dates) in java >
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortByMonth_usingList_overrideComparator2 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Feb");
list.add("Jan");
list.add("Apr");
list.add("Mar");
list.add("June");
list.add("May");
list.add("Aug");
list.add("July");
list.add("Oct");
list.add("Sep");
list.add("Dec");
list.add("Nov");
Collections.sort(list, new Comparator<String>() {
public int compare(String o1, String o2) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
return sdf.parse(o1).compareTo(sdf.parse(o2)); //sdf.parse returns date - So, Compare Date with date
} catch (ParseException ex) {
return o1.compareTo(o2);
}
}
});
System.out.println(list);
}
}
/*output
[Jan, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec]
*/
|
Program to Sort set of month (dates) in java >
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class SortByMonth_usingSet_overrideComparator {
public static void main(String[] args) {
Set<String> set = new TreeSet<String>(new Comparator<String>() {
public int compare(String o1, String o2) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
return sdf.parse(o1).compareTo(sdf.parse(o2)); //Compare Date with date
} catch (ParseException ex) {
return o1.compareTo(o2);
}
}
});
set.add("Feb");
set.add("Jan");
set.add("Apr");
set.add("Mar");
set.add("June");
set.add("May");
set.add("Aug");
set.add("July");
set.add("Sep");
set.add("Oct");
set.add("Dec");
set.add("Nov");
System.out.println(set);
}
}
/*output
[Jan, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec]
*/
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy(JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>