How to sort List<List<String>>

Viewed 497

i got a task to sort text file with some requirements:

  1. sort rows according to columns
  2. sort rows by 1st columns (if data in columns are the same then by second column) and etc. data in rows remains unchanged after sort;
  3. numbers must be sorted in ascending order, and letters in alphabetical order, number goes higher than letter
  4. columns separated with tab ("\t")

what i have done: read file and copy everything in to List>, where every element of List is line from file stored in List here is the code:

public class ReadDataFile {
public static List<List<String>> readData(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName + ".txt"));
    List<List<String>> data = new ArrayList<List<String>>();
    String line;
    while (true) {
        line = br.readLine();
        if (line == null)
            break;
        List<String>lines = Arrays.asList(line.split("\t"));
        data.add(lines);
        System.out.println(lines);
    }
    br.close();
    return data;

and writes data to another file:

    public void writeToFile(String fileName) throws IOException {
    FileWriter writer = new FileWriter(fileName);
    List<List<String>> data = ReadDataFile.readData("input");

    Collections.sort(data, new Comparator<List<String>>() {
        @Override
        public int compare(List<String> o1, List<String> o2) {
            // TODO Auto-generated method stub
            return o1.get(0).compareTo(o2.get(0));
        }
    });

    for (List<String> lines : data) {
        for (int i = 0; i < lines.size(); i++) {
            writer.write(lines.get(i));
            if (i < lines.size() - 1) {
                writer.write("\t");
            }
        }
        writer.write("\n");

    }
    writer.close();
}

the problem is that:

public int compare(List<String> o1, List<String> o2) {
  // TODO Auto-generated method stub
  return o1.get(0).compareTo(o2.get(0));
}

doesn`t sort correctly what i need.

there is example of input file:

-2.2 2 3 4 329 2
2.2 12345q 69 -afg
2.2 12345q 69 -asdf
-22 1234234 asdfasf asdgas
-22 11 abc
-22 -3 4
-1.1
qqqq 1.1

end expected output is:

-22 -3 4
-22 11 abc
-22 1234234 asdfasf asdgas
-2.2 2 3 4 329 2
-1.1
 2.2 12345q 69 -afg
 2.2 12345q 69 -asdf
 qqqq 1.1

but, what i get is:

-1.1
-2.2 2 3 4 329 2
-22 -3 4
-22 11 abc
-22 1234234 asdfasf asdgas
 2.2 12345q 69 -afg
 2.2 12345q 69 -asdf
 qqqq 1.1

the question is, how to write a proper sort? Thanks for the answers

1 Answers
Related