简体   繁体   中英

How do i sort data in text file with Java? vol#2

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM