0

I am writing a Java app which is supposed to read an input file with records on each line and the fields are seperated by commas. The output of the application should be on stdout in format as follows:

Age1
  Sex1
    name1
    name2
  Sex2
    name3
    name4
e.g
33
  Female
    Jayanta
    Kanupriya
44
  Female
    Lajjo
    Rajjo
  Male
    Raghav
    Sitaram

and so on....

I created a class Person to hold the data and implemented the Comparable interface with the compareTo interface doing primary sorting on age and secondary sorting on Sex. I can add tertiary sorting on name later.

public class Person implements Comparable<Person>{

    private String name;
    private int age;
    private String sex;

    /**
     * @param age, sex and name
     */
    public Person(String name, int age, String sex) {
        this.setName(name);
        this.setAge(age);
        this.setSex(sex);

    }

  //getters and setters

    @Override
    public int compareTo(Person person) {
        return this.age < person.getAge()?-1:this.age > person.getAge()?1:sortOnGender(person);
    }

     public int sortOnGender(Person person) {
        if (this.sex.compareToIgnoreCase(person.getSex()) < 0) {
            return -1;
        }
        else if (this.sex.compareToIgnoreCase(person.getSex()) > 0) {
            return 1;
        }
        else {
            return 0;
        }
    }

     @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf(this.age)).append('-').append(this.sex).append('-').append(this.name);
        return sb.toString();
    }
}

Next in the App class in main method I have created an ArrayList of Persons and populated the data and used Collections.sort() to sort. I printed the ArrayList and its coming in sorted order. However the problem is how do I get the data in the desired format.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

public class App {

    //An array of persons
    private static List<Person> persons = new ArrayList<Person>();

    public static void main(String[] args) {

        File inputfile = new File(args[0]);

        if(inputfile.exists()) {
            String line;
            BufferedReader br;
            StringTokenizer st = null;
            try {
                br = new BufferedReader(new FileReader(inputfile));
                // Read comma seperated file line by line
                while((line = br.readLine()) != null) {

                    //Break the line using "," as field seperator
                    st = new StringTokenizer(line, ",");

                    // Number of columns in the line
                    int numcols = st.countTokens();

                    if(numcols > 0) {
                        String[] cols = new String[st.countTokens()];

                        // Till the time columns are there in the line
                        while(st.hasMoreTokens()) {
                            for(int i=0; i < numcols; i++) {
                                cols[i] = st.nextToken();
                            }
                        }

                        // If there are elements in the cols array
                        if(cols.length !=0) {
                            // Create a list of persons
                            persons.add(new Person(cols[0].trim(), Integer.parseInt(cols[1].toString().trim()), cols[2].trim()));
                        }
                    }
                    else {
                        // Print error and continue to next record (Takes care of blank lines)
                        System.err.println("Error: No columns found in line");
                    }
                }
                // Sort the Collection
                Collections.sort(persons);
                br.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

        }
        else {
            System.out.println("Specify the location of the input file");
        }

        System.out.println(persons);

    }
}
5
  • "the desired format" is what exactly? And the format of what? Commented Jul 2, 2014 at 14:48
  • Welcome to SO. What have you tried in your attempt to solve this? Commented Jul 2, 2014 at 14:48
  • It appears as though you want to perform an n-dimensional group by operation, where in your example, n = 2. Guava can help you do this, or you can do it yourself Commented Jul 2, 2014 at 14:50
  • @Daniel - Thanks for the welcome. I have tried to think through the logic, but am not able to figure out how to proceed. Commented Jul 2, 2014 at 14:53
  • @Lutz - Desired format is given at the top. Commented Jul 2, 2014 at 14:55

2 Answers 2

1

I'm not sure I follow you but you just have to write a method that will display as you want !

If you want to print in the console you can try something like :

Public printListPersons(persons[] p){
   for(Person p : persons){
       System.out.println(p[i].getAge);
       System.out.println("\n");
       System.out.println("\t" + p[i].getSex);
       ....
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Once you have a sorted list you should be able to do something like this

int currentAge = -1;
String currentSex = null;

for (Person person : persons) {
    if (person.getAge() != currentAge) {
        currentAge = person.getAge();
        currentSex = null;
        System.out.println(person.getAge());
    }
    if (!person.getSex().equals(currentSex)) {
        currentSex = person.getSex();
        System.out.println("\t" + person.getSex());
    }

    System.out.println("\t\t" + person.getName());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.