-3

I am populating an ArrayList with 2 items from a sql database: An ID and a Date (stored as a string). I want to sort the ArrayList by the Date, and then loop over the sorted array to get back from the database the rest of the information.

Can I achieve this using ArrayList, and if so, HOW? OR

I need to create and populate a different type of Array, if so, what and how to sort it?

I will need to loop over the sorted array to get the rest of the information per record from the database.

I have the following code:

final ArrayList<String> firstList = new ArrayList<String>(); 

while (i<=numRows){
      artID = helper.getTextFromTable(ArticlesTable, i, "achievementID");
      Date = helper.getTextFromTable(ArticlesTable, i, "date");
      firstList.add(artID);
      firstList.add(Date);              
      i= i+1;
    }

I have searched but have not found the answer. Thanks very much.

user3079872
  • 191
  • 1
  • 5
  • 15
  • 2
    check this out http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property http://stackoverflow.com/questions/5894818/how-to-sort-arraylistlong-in-java-in-decreasing-order http://stackoverflow.com/questions/5894818/how-to-sort-arraylistlong-in-java-in-decreasing-order – Quick learner May 18 '15 at 11:57
  • 1
    It looks like you should define a class that has fields for achievementID and date, and populate your list with instances of that. – Steve Chaloner May 18 '15 at 11:59
  • @MD - Thank you, I have seen the other SO questions, but they don't provide the answers I need. I am asking if my current ArrayList can be used, which I think it can't, and if so, what should I use. Thanks for your help. – user3079872 May 18 '15 at 13:11

1 Answers1

0

Use the following one

 Collections.sort(your_array_list);

sort

  • Sorts the specified list in ascending natural order. The algorithm is stable which means equal elements don't get reordered.
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
  • Why you answered such a questions? better to flag it as duplicate becoz already lots of answers available in SO. – M D May 18 '15 at 12:00
  • Thanks, the problem is that I don't think my original Array is set up correct to allow for sorting. So when I finish populating the array i have '[E3, 13-May-2015, E4, 14-May-2015]'; and after the line of code above I get the following: '[13-May-2015, 14-May-2015, E3, E4] – user3079872 May 18 '15 at 12:03
  • It also doesn't solve the problem (see @SteveChaloner's comment) – RobEarl May 18 '15 at 12:06