java - 从文本文件中读取行,并通过将行中的值写入新的文本文件中,按平均值对行中的值进行排序

标签 java arrays sorting text-files java-stream

我有一个文本文件,其中包含以下文本:

输入.txt:

name s1 s2 s3 s4 
Jack 2 4 6 5  
Alex 3 5 5 5 
Brian 6 6 4 5 

现在布莱恩的平均分最高:5.2;亚历克斯:4.5; jack :4.25。 我的任务是获取每个人的平均分数,然后按平均分数升序对人员进行排序,然后使用排序后的值创建一个新的文本文件。

上面的示例在新文本文件中必须如下所示。

输出.txt:

name s1 s2 s3 s4
Brian 6 6 4 5
Alex 3 5 5 5
Jack 2 4 6 5 

到目前为止我想出了2个解决方案,但都无法完成任务。

第一个是:

public class Sort {
    public static void main(String[] args) throws IOException {
        int sortKeyIndex = 0;

        Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
        Path outputFile = Paths.get("C:\\Users\\Desktop\\new-sample.txt");

        String separator = " ";
        Stream<CharSequence> sortedLines =
        Files.lines(inputFile)
             .skip(1)
             .map(sorting -> sorting.split(separator))
             .sorted(Comparator.comparing(sorting -> sorting[sortKeyIndex]))
             .map(sorting -> String.join(separator, sorting));

        Files.write(outputFile, sortedLines::iterator, StandardOpenOption.CREATE);  
    }
}

第二个是:

public class SortTestSecond {
    private static BufferedReader theReader;
    public static void main(String[] args) throws IOException {
        try {
            theReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test2.txt"));
            theReader.readLine();
            String currLine = null;

            while((currLine = theReader.readLine()) != null) {
                System.out.println(currLine);
                StringTokenizer strTok = new StringTokenizer(currLine, " ");
                int theCount=strTok.countTokens();
                int theArray[]=new int[theCount];
                int i = 0;

                while(strTok.hasMoreTokens() && i != theCount) {
                    theArray[i]=Integer.valueOf(strTok.nextToken());
                    i = i + 1;
                }

                int theSum = 0;
                for(int j =0;j < theArray.length; j++) {
                    theSum = theSum + theArray[j];
                }

                float average = (float) theSum / theArray.length;
                System.out.println("Average: " + average);
            }
        } catch(IOException err) {
            err.printStackTrace();
        } finally {
            theReader.close();    
        }
    }
}

最佳答案

一种变体是

Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = inputFile.resolveSibling("new-sample.txt");

String separator = " ", newLine = System.getProperty("line.separator");
Pattern p = Pattern.compile(separator);
try(BufferedReader br = Files.newBufferedReader(inputFile);
    BufferedWriter bw = Files.newBufferedWriter(outputFile, StandardOpenOption.CREATE)) {

    bw.append(br.readLine()).append(newLine); // header
    br.lines()
      .sorted(Comparator.comparingDouble(line ->
          -p.splitAsStream(line).skip(1).mapToInt(Integer::parseInt).average().orElse(-1)))
      .forEachOrdered(s -> {
        try { bw.append(s).append(newLine); }
        catch(IOException ex) { throw new UncheckedIOException(ex); }
    });
}

但是,排序操作无论如何都需要内存中的数据,即使它看起来像流式传输,但它只是隐藏在这里。如果我们接受整个数据都在内存中的事实,我们可以将整个操作简化为:

Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = inputFile.resolveSibling("new-sample.txt");

String separator = " ";
Pattern p = Pattern.compile(separator);

List<String> lines = Files.readAllLines(inputFile);
lines.subList(1, lines.size())
     .sort(Comparator.comparingDouble(line ->
         -p.splitAsStream(line).skip(1).mapToInt(Integer::parseInt).average().orElse(-1)));
Files.write(outputFile, lines, StandardOpenOption.CREATE);

关于java - 从文本文件中读取行,并通过将行中的值写入新的文本文件中,按平均值对行中的值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51099631/

相关文章:

javascript,从大对象数组返回小对象数组

arrays - 从排序数组中选择项目<值的有效方法

java - 再次运行命令时变量不会重置

java - 从 Phonegap HTML5 调用 Java 代码

java - 在 Flex 和 Java 中实现 zLib 压缩

java - 为什么这种类型推断不适用于这个 Lambda 表达式场景?

java - 在 Java 中使用分隔符逗号在嵌套大括号中拆分字符串

javascript - 比较数组内的值、计算它们并合并表中的行

java - Anagram 排序最后一步

c++ - 如何在 C++ 中按字母顺序排序