目前,我只是在文件中對名稱進行排序的位置,但我也希望這樣做,以便年齡可以排序。另一個問題是嘗試獲取相同但具有不同年齡的姓名進行排序。現在我的代碼看起來是這樣的:如何同時對兩個數字和名稱進行排序
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MultiKey {
public static void main(String[] args) {
File textFile = new File("H:\\Names_ages.txt");
FileReader in;
BufferedReader readFile;
String lineOfText;
try {
in = new FileReader(textFile);
readFile = new BufferedReader(in);
BufferedReader reader = new BufferedReader(new FileReader(textFile));
List<String> results = new ArrayList<String>();
while ((lineOfText = readFile.readLine()) != null) {
results.add(lineOfText);
}
Collections.sort(results);
System.out.println(results);
readFile.close();
in.close();
} catch (FileNotFoundException e){
System.out.println("File does not exist or could not be found");
System.err.println("FileNotFoundException: "+ e.getMessage());
} catch (IOException e){
System.out.println("Problem reading file");
System.err.println("IOException: " + e.getMessage());
}
}
}
如果要排序以多種方式您的收藏,您可以通過編寫比較爲此,http://stackoverflow.com/questions/5245093/using-comparator-to- make-custom-sort比較器允許您根據指定的方法對集合進行排序。 – chatton
只是一張紙條,我現在得到的輸出是:[Abrams 15,Alexander 22,Herkman 12,Jones 11,Jones 14,Jones 2,Jones 9,Smith 17,Smith 19,Smith 20,Tippurt 42] –
應該查看['try-with-resources'](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)。 – bradimus