현재 파일 내의 이름 만 정렬 한 시점이지만 나이를 정렬 할 수 있도록 만들고 싶습니다. 또 다른 문제는 동일한 이름을 가지려고하지만 여러 연령대로 분류하려고하는 것입니다.동시에 숫자와 이름을 모두 정렬하는 방법
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- 두를 만드는 elow 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] –
You 또한 [자원을 사용해보십시오 (try-with-resources)] (https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)를 조사해야합니다. – bradimus