[英]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. 我尝试使用Peter Dolberg的Java代码将每一行拆分-但不适用于重复的键。 What can I do instead? 我该怎么办?
Simple approach would be create a class say PersonalInfo with instance variable name,surname,age,weight,height. 一种简单的方法是使用实例变量名称,姓氏,年龄,重量,高度创建一个类PersonalInfo 。 Also write their getter and setter methods. 还要编写他们的getter和setter方法。
Then create an array of PersonalInfo objects(by reading from your file ). 然后创建一个PersonalInfo对象数组(通过从文件读取)。
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. 如果您希望在考虑所有因素的情况下对数据进行排序,则可以将该逻辑添加到Comparator类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.