The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
December 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Not just arrays!!!

Posted by Kishori Sharan on December 10, 2000 at 12:05 AM

There are many ways of solving this. I am going to explain you one which involves only string manipulations.
1) If you are not writing to the file yourself then skip this STEP. If you are wtring to file then write the date in milli seconds format and give a space/tab and then write the name. So your file format will be
Date in Millis Name
878799798902 Kaz

2)Read the whole file one line at a time putting the lines in a string array. So, if there are 10 records then your string array will have 10 elements.
3) Now your problem is to sort the array elements in ascending order on date field. So create a class which implements Comparator interface. Implement the
int compare ( Object a, Object b ) method in this class and write the following lines of code
class Comp implements Comparator {
public int comapare ( Object a, Object b ) {
// Check for valid String arguments etc.
String str1 = ( String ) a ;
String str2 = ( String ) b ;
int pos = 0 ;
// First take out the date part from the strings
if ( str1.length ( ) > 0 ) {
pos = str.indexOf ( " " ) ; // Use space/tab depening what did you use in your file
if ( pos > 0 ) {
str1 = str1.substring ( 0, pos ) ;
}
}
// Do the same processing for str2 as we did for str1
// Now you have two numbers to compare . Convert str1 and str2 into numbers
long date1 = Long.parseLong ( str1 ) ;
long date2 = Long.parseLong ( str2 ) ;

int returnValue = 0 ;
if ( date1 > date2 ) {
returnValue = 1 ;
}
else {
if ( date1 < date2 ) {
returnValue = -1 ;
}
}
return returnValue;
}
}
}

4) Now just pass your String array and an object of Comp class to sort method of Arrays class and you are done.
Arrays.sort ( your_string_array, new Comp ( ) ) ;

5) Print the string array and it will be sorted. However, you will have to convert the milli seconds in a date now.
6) If you already have a file which contains a date in mm/dd/yyyy format or some other format then just your will have to extract the date part in compare method of Comp class and rest you know what to do.

Thanx
Kishori



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us