开发者

Sorting on Last Name

I am reading data from three files and then i want to sort the records on some criteria

Each file has records in the following format

First Name Last Name Gender Color Date

This is the code which i have ... i can sort only on the first name using collections.sort ... how do i sort on other columns ... any help would be appreciated ..

import java.io.BufferedInputStream;
import java.io.*;
import java.sql.*;
import java.io.RandomAccessFile;
import java.io.*;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.Object;
import java.util.Vector;
import java.util.*;

/**
 * This program reads a text file line by line and print to the console. 
 * It uses FileOu开发者_开发问答tputStream to read the file.
 */

public class test1 {    

  public static void main(String[] args) 
    {
          try {

        ArrayList<String> rows = new ArrayList<String>();
        //  ArrayList<String> rows1 = new ArrayList<String>();
    //          ArrayList<String> rows2 = new ArrayList<String>();
    //              ArrayList<String> rows3 = new ArrayList<String>();
    BufferedReader comma = new BufferedReader(new FileReader("C:\\comma.txt"));
    BufferedReader pipe = new BufferedReader(new FileReader("C:\\pipe.txt"));
    BufferedReader space = new BufferedReader(new FileReader("C:\\space.txt"));

    String c= "";
    String p;
    String s;
    while((c = comma.readLine()) != null) {         
            rows.add(c);        
    }

      Collections.sort(rows);
    //  Collections.sort(rows2);

    FileWriter writer = new FileWriter("output.txt");
    for(String cur: rows)
    {        
        writer.write(cur+"");          
    }
   //  for(String cur: rows1)
    //  writer.write(cur+"\n");
     // for(String cur: rows2)
      // writer.write(cur+"\n");
    comma.close();
  //  pipe.close();
  //  space.close();
    writer.close();

          }
     catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }        
  }
}


You are currently sorting lexically based on the string representing an entire line. In your file format, the line starts with first names, so that's what you are using to sort.

If you want to sort by last name, you really have no way but to parse each line so that the program can identify the last name. That will make your program a lot more complex.

You can use a StringTokenzier or a regular expression to identify the last name in the string. Then you can use a custom comparator to sort based on that.

A more OOP way is to represent each record as an object, and then use Collections.sort() using a custom comparator based on its fields. It's lengthy, but it's the correct "object oriented way".

If you just want a quick and dirty solution, you may want to use a language more appropriate for text manipulation, like Perl or Python...


You need to parse your data into real objects or arrays, then you can pass a comparator to sort asking it to sort on last name.

Alternately, you could do this with a complicated comparator and a string that has the fields separated, but it's not the right way to do it, and will be more painful than the first option.


1) Create an Object with the following properties:

lastName, firstName, sex, birthdate

then create getter methods for each property.

2) Read each line of data from the file and create the above Object with the parsed data

3) Add each Object to your ArrayList

4) Then you can use the BeanComparator and/or GroupComparator to sort on any field or group of fields.


Use:

Collections.sort(List list, Comparator c)

The Comparator determines how the items in the list are sorted. You first need to build a list of objects to sort.


Use Collections.sort(List, Comparator) instead of Collections.sort(List). You can make your own custom implementation of the Comaparator interface that compares your three criteria (gender, lastname, date) in the specific way you want and pass it as the second argument to Collections.sort().


I think the easiest way at this point would be to create your own class with fields for each property. You could define separate comparators ([http://java.sun.com/javase/6/docs/api/java/util/Comparator.html])1 or make the class comparable with a compareTo() method and a switch to determine how the fields are compared.


The key here is to create a simple Java class representing each row (each has fields for first name, last name, gender, color, and date). Let's call that class Person.

Then you replace your ArrayList<String> with an ArrayList<Person>:

List<Person> people = new ArrayList<Person>();  

And as you read your data in, don't store each row as a String, but create a new Person object from it, and add it to people.

To sort people in different ways, you have to create another class for each kind of sort. Each must implement the Comparator interface, which means it has a single method called compare which compares two People and replies which one sorts first.

Then you can sort the list in different ways, eg, to put it in order of birthdate:

Collections.sort(people, new BirthdayComparator());

Good luck on your homework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜