0

I'm trying to sort data I have in a text file. Each row of the file contains the fields:

name,surname,age,weight,height

I tried to split each line up by using Peter Dolberg's Java code - but it doesn't work for duplicate keys. What can I do instead?

Community
  • 1
  • 1
Kaan Eroğlu
  • 63
  • 1
  • 7
  • 1) Please add an upper case letter at the start of sentences. Also use a capital for the word I & proper names like Java, and abbreviations and acronyms like JEE or WAR. This makes it easier for people to understand and help. 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson May 19 '13 at 08:16
  • You can use [Sort ArrayList of custom Objects by property][1] [1]: http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – Ilya Gazman May 19 '13 at 08:23

1 Answers1

1

Simple approach would be create a class say PersonalInfo with instance variable name,surname,age,weight,height. Also write their getter and setter methods.

Then create an array of PersonalInfo objects(by reading from your file ).

PersonalInfo employeeInfo[] = new PersonalInfo[3];

Then define a Comparator on the basis you would like to compare. For example for age -

 class AgeComparator implements Comparator{

public int compare(Object ob1, Object ob2){
    int ob1Age = ((PersonalInfo)ob1).getAge();        
    int ob2Age = ((PersonalInfo)ob2).getAge();

    if(ob1Age > ob2Age)
        return 1;
    else if(ob1Age < ob2Age)
        return -1;
    else
        return 0;    
  }
}

Then you can simply use this comparator to sort your data.

Arrays.sort(employeeInfo, new AgeComparator());

If you wish to sort the data taking all factors into consideration then you can add that logic to your Comparator class.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289