Show Default Model Year


General J2EE: Show Default Model Year

  1. Show Default Model Year (1 messages)

    Hello All,

    I have a Java code which fetches SQL to populate the drop down box.

    SQL is returning result in this order -

    year_code year_description
    5 2005
    4 2004
    3 2003
    2 2002

    The drop down build from the java program is showing the same order

    However, I want to show the order like


    How can I default the year code to 2004 when the SQL is returning the above order

    What change I may need to incorporate in Java code or SQL ?? A code snippet will expedite and help me a lot.

    Thanks for your feedback

    Threaded Messages (1)

  2. Show Default Model Year[ Go to top ]

    How exactly do you want to sort these? Current year first, then all other years in reverse order?

    Doing bizaar sort operation can be hard in SQL, but not too bad in Java. The best way to handle this is with a java.util.Comparator that specifies your sort order. Here is a sketch, assuming your store your years as Integer objects.

    public class YearComparator implements Comparator {
      public int compare(Object o1, Object o2) {
        Integer year1 = (Integer) o1;
        Integer year2 = (Integer) o2;
        if (year1.equals(year2)) return 0;

        // Current year at the top:
        Calendar now = Calendar.getInstance();
        Integer currentYear = new Integer(now.get(Calendar.YEAR));
        if (year1.equals(currentYear)) return 1;
        if (year2.equals(currentYear)) return -1;

        // Otherwise, sort in reverse order:
        return (year2.intValue() - year1.intValue());

    You can then sort the collection containing your years:

    Collections.sort(years, new YearComparator());

    Alternately, you can store your data in a tree map that uses your Comparator to determine sort order:

    Map yearMap = new TreeMap(new YearComparator());