Thursday 15 September 2011

java - How to sort a list of months with years -


I have a list of months with years like: [12-2014, 11-2012-2015- 2014, 8-2012] and I have to sort them with the most recent (or the latest date at the top) e.g. [12-2014-2014,11-2012,8-2012]
Does anybody know how this can be done efficiently in java ?

Edit:
Class year is not available, I on Java 7

Since you are using Java 7, you take advantage of comparative interface along with the date class Use it for example in tree set such as set object.

Here is the implementation of the comparative interface to compare two dates

  Public category month comparison Comparison Tools Comparative & lt; Date & gt; {Compare Public Entry (Date O1, Date O2) {// TODO Auto generated method stub Return -1 * o1.compareTo (o2); }}  

and then how we can use it. First of all, I will parse my string in the form of dates by using a simple data format class. To do this, I need to complete them and show them the outline date string. Since the day is irrelevant to the comparison because I can take any day like "01".

Once I change them into dated objects, they are paired with an example of a tree resource which is provided with a comparative and will be automatically sorted as That I add them

Then I can reduce the part of the date that I need, which is a substring (3) of my dated object after being formated in the string.

Here's the code (for the demo I used the same thing that you provided in the example):

  import java.text.ParseException; Import java.text.SimpleDateFormat; Import java.util.ArrayList; Import java.util.Date; Import java.util.list; Import java.util.Set; Import java.util.TreeSet; Public Sector Mahanairi ISEE {Private List & lt; String & gt; ListOfMonthYears = new ArrayList & lt; String & gt; (); Private Stable Last String USED_DATE_FORMAT = "dd-MM-yyyy"; SimpleDateFormat formatter = New SimpleDateFormat (USED_DATE_FORMAT); Public Zero Setup Monotheist () {listOfMonthYears.add ("12-2014"); ListOfMonthYears.add ("11-2012"); ListOfMonthYears.add ("5-2014"); ListOfMonthYears.add ("8-2012"); } Public Date Parsadodet (String Month Yeester String) throws ParseException {Return Formater. From ("01-" + Month Rain String); } Public listing & lt; String & gt; DoSort () throws ParseException {list & lt; String & gt; Results = New Arreelist & lt; String & gt; (); Set up & lt; Date & gt; Date = new tree set & lt; Date & gt; (New month year commuter ()); For (string month year: listoffmonites) {dates.add (parseToDate (month YESStr)); } (Object D: Dates.Tore ()) {result.add (formatter.format (date) D). Asbestring (3)); } System.out.println (results); Return result; } Public static zero main (string [] args throws ParseException {MonthYearIssue issueSolver = new MonthYearIssue (); IssueSolver.setUpMonthYearsList (); IssueSolver.doSort (); }}  

The result is:

[12-2014, 05-2014, 11-2012, 08-2012]


No comments:

Post a Comment