简体   繁体   中英

sorting file ouput in ascending order

import java.util.*;
import java.io.*;


public class MarksProcess {
public static void main (String[] args)throws Exception{
    File inFile = new File ("hello.txt");
    Scanner input = new Scanner(inFile);

    while (input.hasNext()){
        String line = input .nextLine();
        System.out.println(line);

    }
    input.close();

}
}

The output of my file is:

345493 Jim
123464 Pete
123234 Jay

How do I sort the output of the text file in ascending order by using the student number so it will look like this:

123234 Jay
123464 Pete
345493 Jim

To order the result simply add them to a list then sort this list :

List<String> eachRows = new ArrayList<>();
while (input.hasNext())
    eachRows.add(input.nextLine());

input.close();

Collections.sort(eachRows);
for(String s : eachRows)
    System.out.println(s);

Or with java 8 :

eachRows.stream()
    .sorted()
    .forEach(row -> System.out.println(row));

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