Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

sort array column 5

6 views
Skip to first unread message

bender bender

unread,
Mar 9, 2021, 12:54:41 PM3/9/21
to
Hi,
I'm scripting a java program that sort descending data from csv file

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;


public class javaRes {

// Sort column csv

static class OrderColumn

{
public static void main (String[] args) throws IOException

{
File fileCSV = new File("Analisi_2018.csv");
BufferedReader streamCSV = new BufferedReader(new FileReader(fileCSV));

//Instantiating the File class
File file = new File("provvi.csv");
//Instantiating the PrintStream class
PrintStream stream = new PrintStream(file);
System.setOut(stream);

String lineRead;

int tmpRowCount=0;

while( (lineRead=streamCSV.readLine()) != null )
{
tmpRowCount++;
}

streamCSV.close();

System.out.println("Rowcount= "+tmpRowCount);

String[] fileArray=new String[tmpRowCount];

streamCSV = new BufferedReader(new FileReader(fileCSV));

int tmpI=0;

while( (lineRead=streamCSV.readLine()) != null )

{

fileArray[tmpI++]=lineRead;

}
//SORT HERE


Arrays.sort(fileArray, Collections.reverseOrder());

for (String number : fileArray) {
System.out.println(number);
}



System.exit(1);

}

}

}

I obtain a new .csv
but sorting about column 1
I would order with target column 6
How could fix it using this scheme of program

regards

A

Dr.UgoGagliardelli

unread,
Mar 10, 2021, 1:46:53 AM3/10/21
to
Consider that Collections.reverseOrder() has type Comparator and you are
comparing String objects, so for that you sort for column 1 that's the
beginnig of the row. You shoud use a custom Comparator that compare
column 6. For example;
Comparator comparator = new Comparator<String>() {
public int compare(String o1, String o2) {
int comp = o2.compareTo(o1);
return comp;
}
}
for ascending order reverse the comparison to o1.compareTo(o2); so your
statement would be Arrays.sort(fileArray, comparator); tha's not
different from Collections.reverseOrder().
Now the problem is parsing strings to get 6th column from both o1 and o2
inside the method compare.
One trivial way could be compare the substring between 5th and 6th
comma-separator, e.g.:

public int compare(String o1, String o2) {
String[] a1 = o1.split(","), a2 = o2.split(",");
int comp = a2[5].compareTo(a1[5);
return comp;
}

but it's a weak way, as some text column can have the comma-separator
part of the text. Doing a stronger job is like reinventing the wheel:
there are plenty of java libraries, most of them open-source, that
extract columns from each row.
0 new messages