1

I have a string like

String str[]={"jan2011","feb2011","jan2010,"mar2012"};

How do I sort this by Date like: jan2010,jan2011,feb2011,mar2012

thanks for advance(not to use string functions more )

2 Answers2

0

Hoi:

String[] unsorted={"jan2011","feb2011","jan2010","mar2012"};
List<String> unsortedList = Arrays.asList(unsorted);
Collections.sort(unsortedList);
String[] sorted = (String[])unsortedList.toArray();

This should do...

Gruber
  • 531
  • 1
  • 6
  • 17
  • @gruber that will sort alphabetically, not by date – fvu May 30 '11 at 13:43
  • thank u fnd but i am developing a blackberry application so here collections not working –  May 30 '11 at 13:44
  • @govind I'm a bit confused now, what exactly are you looking for? a sort function in Java? – fvu May 30 '11 at 13:47
  • your code is not working in java also because if in string array all strings either strings or numbers then it is working but in my string it is not working –  May 30 '11 at 13:49
  • @fvu sir actully java collection functions working in if string array contain all strings either strings or numbers but i need short above string array plz help me –  May 30 '11 at 13:53
0

Assuming you have version 6 at your disposal, you can use the built-in

Collections.insertionSort(datavector, comparator);

However:

  • you'll need to move your strings into a Vector
  • you'll need to provide a Comparator class for your specific needs

The Comparator class could be something along these lines:

public class DatestringComparator implements Comparator{

    public int compare(String s1, String s2) {
        // create Date instance based on the content of the input string
        Date d1 = ....; 
        Date d2 = ....;
        return d1.compareTo(d2);
    }
}
fvu
  • 32,488
  • 6
  • 61
  • 79
  • thank u sir, but i did not get this plz provide me code for my requirement –  May 30 '11 at 14:26