Get a Column after Sorting

Question

I have a two-column CSV file as input and want to sort data by date column (dd/mm/yyyy). The following code sorts the date correctly but I want the related value with that date.

I run the code to get this:

02/05/2012

09/11/2012

10/11/2012

 

The code:

public static void main(String[] args){

  Date value = null;

String reader ="";

String[] input = null ;

Date date;

List<Date> dateList = new ArrayList<Date>();

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

File file = new File("data.csv");

 

try {

BufferedReader br = new BufferedReader(new FileReader(file));

while((reader = br.readLine())!=null){

input = reader.split(",");

date = df.parse(input[0]);

dateList.add(date);

}

 

Collections.sort(dateList, new Comparator<Date>() {

public int compare(Date o1, Date o2){

return o1.compareTo(o2);

}

});

 

for(Date x : dateList){

System.out.println(df.format(x));

}

 

} catch (FileNotFoundException fi) {

fi.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 } catch(ParseException pe){

pe.printStackTrace();

}

}

 

Answer

It’s one of the basic structured computations to sort records and get values of a certain filed. As Java lacks related class library, you need to write a lot of code to do this. In this case try using SPL (Structured Process Language) to handle the computation for Java.

Suppose the source data looks like this:

date,value

10/11/2012,300

02/05/2012,100

09/11/2012,200

 

SPL script:

A

1

=file("d:\\data.csv").import@t(;,",")

2

=A1.sort(date).(value)

A1: Read into the CSV file.

A2: Sort records by date and get corresponding values.

undefined

About calling an SPL script in a Java application, see How to Call an SPL Script in Java.