Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

sorting problem

  Asked By: Fern    Date: Nov 23    Category: Java    Views: 736
  

i had dir names as follows
JAN2004,SEP2004,FEB2005,AUG2004 etc.........
now these should be displyed in a Sorting order
according to mon and next year
ie.

JAN2004,AUG2004,SEP2004,FEB2005

so any body plz explain me
i am very new to java
if u had plz provide me an example also

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Wade Jordan     Answered On: Nov 23

Here is solution for you, just convert that strings into date format and sort it
out

 
Answer #2    Answered By: Roderick King     Answered On: Nov 23

Here is simpler solution
Just compare two strings there is a function forgot name but go to String class
descirption on java.sun.com and you will find all sorts of functions that will
help operate on string, one of them ofcourse is string compare

 
Answer #3    Answered By: Fatih Farooq     Answered On: Nov 23

Simple string comaprisions wont work here. APR2004 will be sorted sequentially
MAR2004. Many such situations may occur. Best Solution will be coverting to date
format based. This could be done in more than one way. Dumb rule would be to get
a substring of first three positions as month and last four positions as year
and implement some sort logic.

 
Answer #4    Answered By: Isaac Evans     Answered On: Nov 23

I tried & it's working fine... u can use it... (change the dir name to ur dir)


import java.io.*;
import java.text.*;

public class DateSort
{
public static void main(String args[])
{
try
{
SimpleDateFormat sdfDate = new SimpleDateFormat("MMMyyyy");
File fDir = new File("C:\\Vasanth\\Java\\MyDirectory");
File files[] = fDir.listFiles();
long lDates[] = new long[files.length];

for(int i=0;i<files.length;i++)
{
lDates[i] = sdfDate.parse(files[i].getName()).getTime();
}

for(int i=0;i<lDates.length;i++)
{
for(int j=0;j<i;j++)
{
if(lDates[i] < lDates[j])
{
File fTemp = files[i];
long lTemp = lDates[i];

files[i] = files[j];
lDates[i] = lDates[j];

files[j] = fTemp;
lDates[j] = lTemp;
}
}
}

for(int i=0;i<files.length;i++)
{
System.out.println(files[i].getName());
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}

 
Didn't find what you were looking for? Find more on sorting problem Or get search suggestion and latest updates.




Tagged: