1

I have a list of ArrayList, and each arraylist consists of a date and a string. I want to sort the list according to the date in the arraylist. I tried looking for answers but cant find it online. Most of the examples are sorting a list of objects by date. Any suggestions?

public List<ArrayList> SuggestionReport() {
    Query q = em.createQuery("SELECT s FROM SuggestionEntity s");
    List<ArrayList> report = new ArrayList();
    for (Object o : q.getResultList()) {
        suggestionEntity = (SuggestionEntity) o;
        ArrayList suggestion = new ArrayList();
        suggestion.add(suggestionEntity.getSuggestionDate());
        suggestion.add(suggestionEntity.getContent());
        report.add(suggestion);
    }

    return report;
}

ps. I want to sort the list before returning the list

ayampenyet
  • 241
  • 1
  • 2
  • 15
  • 2
    you can query by date.try this sql "SELECT s FROM SuggestionEntity s order by s.suggestionDate desc".the "s.suggestionDate" is your database field .than the result was sort already. – Blade Master Oct 12 '13 at 08:38
  • http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – Salem Oct 12 '13 at 08:41

2 Answers2

4

Need not to write extra code, Just change your query to

SELECT s FROM SuggestionEntity s order by  suggestion_date ASC|DESC

Where suggestion_date is your column name.

ASC|DESC is order you want, choose ASC or DESC based on your requirment.

Learn more here about order by

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You should write your own comparator, and then sort it like following:

Collections.sort(list, myComparator);