views:

559

answers:

8

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 FileOutputStream 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();
    }        
  }
}
+1  A: 

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.

Kevin Peterson
A: 

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.

RMorrisey
A: 

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().

Asaph
+2  A: 

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...

Uri
A: 

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%5D%29%5B1%5D or make the class comparable with a compareTo() method and a switch to determine how the fields are compared.

Rob Lourens
A: 

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.

Jim Ferrans
A: 

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.

camickr
A: 

thx so much for the response guys ... i am able to solve my problem to a great extent ... but now i cannot sort on the gender ...

i want this output :-

Output 1: Hingis Martina Female 4/2/1979 Green Kelly Sue Female 7/12/1959 Pink Kournikova Anna Female 6/3/1975 Red Seles Monica Female 12/2/1973 Black Abercrombie Neil Male 2/13/1943 Tan Bishop Timothy Male 4/23/1967 Yellow Bonk Radek Male 6/3/1975 Green Bouillon Francis Male 6/3/1975 Blue Smith Steve Male 3/3/1985 Red

but the output which i am getting is :-

Output 1:Kelly Sue Female01/12/1959 PinkAbercrombie Neil Male01/13/1943 TanBishop Timothy Male01/23/1967 YellowKournikovaAnnaFemale06/03/1975RedHingisMartinaFemale04/02/1979GreenSelesMonicaFemale12/02/1973BlackSmithSteveMale01/03/1985RedBonkRadekMale01/03/1975GreenBouillonFrancisMale01/03/1975Blue

i cannot sort on the gender ... this is only the problem now ...

I have three files each having 3 records in the form :-

Last Name, First Name, Gender, Favorite Color, Date Of Birth

the second and third files have records of the following format Last Name, First Name, Middle Initial, Gender, Date Of Birth, Favorite Color Last Name, First Name, MiddleInitial, Gender, Favorite Color, Date Of Birth

in the second and third files i am reading the gender at the third position in the array becuase they have 6 records and in the first file it has 5 records ... so in order to read gender at third postion in the first file i added a null padding in the array so i can sort properly on gender ... but still no luck .... please help me guys

the following is my code :-

main class

[code]

import java.io.; import java.sql.; import java.lang.; import java.util.; import java.text.*; import java.util.Vector; import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.ListIterator; import java.util.List; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date;

public class test1 {

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

ArrayList<Person> personList = new ArrayList<Person>();


    // reading data from three files  
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;
String paddedTokens[] =  {" "," "," "," "," "," "};
Person person =new Person();
while((c = comma.readLine()) != null ) 
 {

  String tokens[] = c.split(",");

   try
     {
       paddedTokens[0] = tokens[0];
       paddedTokens[1] = tokens[1];
       paddedTokens[2] = " ";
       paddedTokens[3] = tokens[2];
       paddedTokens[4] = tokens[3];
       paddedTokens[5] = tokens[4];
       String strDate = paddedTokens[5];
       System.out.println("Array Element 1" +paddedTokens[0]);
        System.out.println("Array Element 2" +paddedTokens[1]);
         System.out.println("Array Element 3" +paddedTokens[2]);
          System.out.println("Array Element 4" +paddedTokens[3]);
           System.out.println("Array Element 5" +paddedTokens[4]);
                   System.out.println("Array Element 6" +paddedTokens[5]);

 SimpleDateFormat sdfSource = new SimpleDateFormat("mm/dd/yyyy");
 Date strnDate = sdfSource.parse(strDate);
 Person personcom = new Person();
 personcom.setLast_name(paddedTokens[0]);
 personcom.setFirst_name(paddedTokens[1]);
 personcom.setGender(paddedTokens[3]);
 personcom.setColor(paddedTokens[4]);
 personcom.setDate(strnDate);
 personList.add(personcom);

} catch(ParseException e) { System.out.println("Invalid Date Parser Exception "); e.printStackTrace(); }

}

 while((p = pipe.readLine()) != null )

{

String delims = "[ | ]+"; String tokens[] = p.split(delims); String strDate = tokens[5]; String strnewDate = strDate.replace("-","/"); try { SimpleDateFormat sdfSource = new SimpleDateFormat("mm/dd/yyyy"); Date strnDate = sdfSource.parse(strnewDate); String strgender = tokens[3]; String strnewgender = strgender.replace("M","Male");

Person personpipe = new Person(); personpipe.setLast_name(tokens[0]); personpipe.setFirst_name(tokens[1]); personpipe.setGender(strnewgender); personpipe.setColor(tokens[4]); personpipe.setDate(strnDate);

  personList.add(personpipe);

} catch(ParseException e) { System.out.println("Invalid Date Parser Exception "); e.printStackTrace(); }

} System.out.println("List" + personList); while((s = space.readLine()) != null ) {

String tokens[] = s.split(" "); String strDate = tokens[4]; String strnewDate = strDate.replace("-","/"); try {

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); Date formDate = df.parse(strnewDate); String strgender = tokens[3]; String strnewgender = strgender.replace("F","Female");

Person personspc = new Person(); personspc.setLast_name(tokens[0]); personspc.setFirst_name(tokens[1]); personspc.setGender(strnewgender); personspc.setColor(tokens[5]); personspc.setDate(formDate); personList.add(personspc);
} catch(Exception e) { System.out.println("Invalid Date Parser Exception "); e.printStackTrace(); }

}

Iterator it=personList.iterator();

while(it.hasNext())

{ Person itperson =(Person) it.next(); }

// Collections.sort(personList,new DateComparator());

Collections.sort(personList,new GenderComparator());

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); FileWriter writer = new FileWriter("output.txt"); writer.write("Output 1:"); it=personList.iterator(); while(it.hasNext()){

  Person itperson =(Person) it.next();
  writer.write(itperson.getLast_name());
  writer.write(itperson.getFirst_name());
  writer.write(itperson.getGender());
  writer.write(df.format(itperson.getDate()));
  writer.write(itperson.getColor());
}

Collections.sort(personList,new DateComparator()); writer.write("Output 2:"); it=personList.iterator(); while(it.hasNext()) { Person itperson =(Person) it.next(); writer.write(itperson.getLast_name()); writer.write(itperson.getFirst_name()); writer.write(itperson.getGender()); writer.write(df.format(itperson.getDate())); writer.write(itperson.getColor()); }

ListIterator itcmp = personList.listIterator(); Collections.sort(personList,new LastNameComparator()); writer.write("Output 3:"); itcmp=personList.listIterator(); while(itcmp.hasNext()) { Person itperson =(Person) itcmp.next(); } while(itcmp.hasPrevious()) { Person itperson =(Person) itcmp.previous(); writer.write(itperson.getLast_name()); writer.write(itperson.getFirst_name()); writer.write(itperson.getGender()); writer.write(df.format(itperson.getDate())); writer.write(itperson.getColor()); }

comma.close(); pipe.close(); space.close(); writer.close();

   }

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

} }[/code]

gender comparator :-

[code] import java.io.; import java.sql.; import java.lang.Object; import java.util.Vector; import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date;

public class GenderComparator implements Comparator{

public int compare(Person e1, Person e2) { int result;

result = e1.getGender().compareTo(e2.getGender()); if (result != 0) { return result; }

return result; }

} [/code]

Person class

[code]

import java.io.; import java.sql.; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat;

public class Person {

private String first_name; private String middle_init; private String last_name; private String gender; private String color; private Date date;

public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getMiddle_init() { return middle_init; } public void setMiddle_init(String middle_init) { this.middle_init = middle_init; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; }

}

[/code]

Last Name Comparator

[code]

import java.io.; import java.sql.; import java.lang.Object; import java.util.Vector; import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator;

public class LastNameComparator implements Comparator {

public int compare( Person a, Person b ) { return a.getLast_name().compareTo(b.getLast_name()); }

}

[/code]

Date Comparator :-

[code]

import java.util.Vector; import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date;

public class DateComparator implements Comparator{

public int compare( Person a, Person b )

                    {
                    return( (Date)a.getDate() ).compareTo( (Date) b.getDate() );
                    }

}

[/code]

This isn't an answer. If you want to ask another question, then add to your original question (by editing it), or ask a brand new question.
ChrisW