rahul k
rahul k

Reputation: 1

how to sort the list<Date, String> in Java according to Date

I have some table names coming as i/p param to my method. I need to get the creationDate (date), count for each table and put it in a consolidated List)

and then Sort the list according to the creationDate.

Here is the Method:

public String getData(List tablename){
    Lifecycle.beginCall();
    EntityManager mgr = (EntityManager) Component.getInstance("entityManager");
    List data = new ArrayList();
    if (!tablename.isEmpty())
    {
        Iterator itr = tablename.iterator();
        while(itr.hasNext())
        {
            String element = itr.next().toString();
            Query q = mgr.createQuery("select to_date(s.creationDate), count(s)" +
                                      " from " + element + " s" +
                                      " group by to_date(creationDate)" +
                                      " order by to_date(creationDate)");
            List dataTemp = q.getResultList();

            data.addAll(dataTemp);

        }
    }
}

Now I have List data, e.g.:

({["Jan 3, 2013 12:00:00 AM",10],
  ["Feb 3, 2013 12:00:00 AM",10],
  ["Jan 1, 2013 12:00:00 AM",10],
  ..........})

Challenge here is i want this List to be sorted according to the date

Upvotes: 0

Views: 2383

Answers (3)

radai
radai

Reputation: 24202

have a look at Collections.sort(). all you need to do is write a class that implements a Comparator<Date> and provide it along with your list to be sorted.

even better, since Date is already Comparable, you can just call Collections.sort(data) and it will be sorted in ascending order.

EDIT: upon closer inspection your list (data) does not contain Date objects, its actually a List with each element being an object array of size 2 - the 1st item in the array is the table creation date and the 2nd is the row count. so you need to sort like this:

Collections.sort(data, new Comparator<Object> {
    @Override
    public int compare(Object o1, Object o2) {
        Object[] a1 = (Object[]) o1;
        Object[] a2 = (Object[]) o2;
        Date d1 = (Date) a1[0];
        Date d2 = (Date) a2[0];
        return d1.compareTo(d2);
    }
});

Upvotes: 1

kan
kan

Reputation: 28981

As I see, you select from several tables. You could compose one SQL query using UNION to select all records by the one query. This is very similar query: SQL Query - Using Order By in UNION.

Upvotes: 0

Sudhakar
Sudhakar

Reputation: 4873

Simplest way is to do the sorting at the DB level.

Change your query to

       Query q = mgr.createQuery("select to_date(s.creationDate), count(s)" +
                                  " from " + element + " s" +
                                  " group by to_date(creationDate)" +
                                  " order by creationDate asc");

Upvotes: 0

Related Questions