我读了一个文件,其中每一行都是这样的:
userName
,age
,award
我需要编写两种排序类型:by userName
和by age
。我对第一个问题没有任何问题,但我不知道在这样的例子中如何按年龄排序。
我尝试在每行中使用年龄切换名称,但它不起作用。
这就是我所拥有的(它基本上只是从文件中读取并显示它):
try{
File file=new File(path);
BufferedReader read=new BufferedReader(new FileReader(file));
String line=read.readLine();
all+=line+"\n";
while(line!=null){
line=save.readLine();
all+=line+"\n";
}
String [] tabUsers=all.split("\n");
String display="";
for(int a=0;a<tabUsers.length-1;a++){
display+=tabUsers[a]+"\n";
}
for(int c=0;c<tabUsers.length-1;c++){
System.out.println(tabUsers[c]);
}
}
catch(Exception ex){
}
有什么想法吗?
我试过这个,但它不起作用:
for(int b=0;b<tabUsers.length-1;b++){
String eachLine =tabUsers[b];
String [] splitLine=eachLine.split(",");
splitLine[0]=splitLine[1];
}
答案 0 :(得分:1)
将您的数据读入这样的对象集合中:
public class User {
final String name;
final int age;
final String award;
public User(String name, int age, String award) {
this.name = name;
this.age = age;
this.award = award;
}
}
然后使用Collections.sort
和Comparator<User>
进行排序:
User bob = new User("Bob", 44, null);
User zack = new User("Zack", 13, null);
List<User> users = Arrays.asList(bob, zack);
//sort by age
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
return Integer.compare(user1.age, user2.age);
}
});
//sort by name
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
return user1.name.compareTo(user2.name);
}
});
答案 1 :(得分:0)
首先从每一行获取名称和年龄。然后你可以将东西放在两个treeMaps上,一个是Names键,另一个是Age键。类似的东西:
String[] lines = new String[3];
lines[0] = "Michael 25 Award_1";
lines[1] = "Ana 15 Award_2";
lines[2] = "Bruno 50 Award_3";
String[] parts;
Map<String, String> linesByName = new TreeMap<String, String>();
Map<Integer, String> linesByAge = new TreeMap<Integer, String>();
for (String line : lines) {
parts = line.split(" ");
linesByName.put(parts[0], line);
linesByAge.put(Integer.parseInt(parts[1]), line);
}
System.out.println("Sorted by Name:");
for (Map.Entry<String, String> entry : linesByName.entrySet()) {
System.out.println(entry.getValue());
}
System.out.println("\nSorted by Age:");
for (Map.Entry<Integer, String> entry : linesByAge.entrySet()) {
System.out.println(entry.getValue());
}