【问题标题】:How can I sort a Ranking list using a specific column from a file and print the whole file sorted?Java如何使用文件中的特定列对排名列表进行排序并打印已排序的整个文件?Java
【发布时间】:2019-05-14 22:47:17
【问题描述】:

已经这样做了,但不能让它工作。

还尝试创建另一个 while ((line = br.readLine()) != null) {},并将排序放在它之前,但它不会读取这个 while,所以它不会打印任何东西。

文件如下所示:

    1-Fred-18-5-0

    2-luis-12-33-0

    3-Helder-23-10-0

并希望它像这样打印:

    2-luis-12-33-0

    3-Helder-23-10-0

    1-Fred-18-5-0

public static void lerRanking() throws IOException {
        File ficheiro = new File("jogadores.txt");

        BufferedReader br = new BufferedReader(new FileReader(ficheiro));
        List<Integer> jGanhos = new ArrayList<Integer>();
        int i = 0;
        String line;
        String texto = "";

        while ((line = br.readLine()) != null) {

            String[] col = line.split("-");
            int colunas = Integer.parseInt(col[3]);
            jGanhos.add(colunas);

            i++;
            if(i>=jGanhos.size()){
                Collections.sort(jGanhos);
                Collections.reverse(jGanhos);
                for (int j = 0; j < jGanhos.size(); j++) {
                    if(colunas == jGanhos.get(i)){
                        texto = texto + line + "\n";    
                    }
                }
            }
        }    
        PL(texto);
}

【问题讨论】:

  • 你能给我们一个输入示例吗?
  • 已经做了,不知道大家能不能看懂。
  • 如果您为您的数据创建一个自定义类会更好,这样您就可以将值保持在一起。

标签: java file sorting columnsorting


【解决方案1】:

一步一步来:

public static void lerRanking() throws IOException {
    File ficheiro = new File("jodagores.txt");

    // read file
    BufferedReader br = new BufferedReader(new FileReader(ficheiro));
    List<String> lines = new ArrayList<>();
    String line;
    while ((line = br.readLine()) != null) {
        lines.add(line);
    }

    // sort lines
    lines.sort(new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            // sort by 3rd column descending
            return Integer.parseInt(s2.split("-")[3]) - Integer.parseInt(s1.split("-")[3]);
        }
    });

    // concat lines
    String texto = "";
    for (String l : lines) {
        texto += l + "\n";
    }

    System.out.println(texto);

    // PL(texto);

}

【讨论】:

    【解决方案2】:

    好的,首先我认为你应该引入一个 Java 类(在我的代码中是 ParsedObject)来管理你的对象。

    其次,它应该实现Comparable&lt;ParsedObject&gt; 接口,因此您可以轻松地从代码中的任何位置对其进行排序(无需每次都传递自定义比较器)。

    这里是完整的代码:

    import java.io.*;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
            lerRanking();
        }
    
        public static void lerRanking() throws IOException {
            File ficheiro = new File("jodagores.txt");
            // read lines to a list
            List<String> lines = readLines(ficheiro);
            // parse them to a list of objects
            List<ParsedObject> objects = ParsedObject.from(lines);
            // sort
            Collections.sort(objects);
            // print the output
            writeLines(objects);
        }
    
        public static List<String> readLines(File ficheiro) throws IOException {
            // read file line by line
            BufferedReader br = new BufferedReader(new FileReader(ficheiro));
            List<String> lines = new ArrayList<>();
            String line;
            while((line = br.readLine()) != null) {
                lines.add(line);
            }
            br.close(); // THIS IS IMPORTANT never forget to close a Reader :)
            return lines;
        }
    
        private static void writeLines(List<ParsedObject> objects) throws IOException {
            File file = new File("output.txt");
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            for(ParsedObject object : objects) {
                // print the output line by line
                bw.write(object.originalLine);
            }
            bw.flush();
            bw.close();  // THIS IS IMPORTANT never forget to close a Writer :)
        }
    
    
        // our object that holds the information
        static class ParsedObject implements Comparable<ParsedObject> {
    
            // the original line, if needed
            public String originalLine;
            // the columns
            public Integer firstNumber;
            public String firstString;
            public Integer secondNumber;
            public Integer thirdNumber;
            public Integer fourthNumber;
    
            // parse line by line
            public static List<ParsedObject> from(List<String> lines) {
                List<ParsedObject> objects = new ArrayList<>();
                for(String line : lines) {
                    objects.add(ParsedObject.from(line));
                }
                return objects;
            }
    
            // parse one line
            public static ParsedObject from(String line) {
                String[] splitLine = line.split("-");
                ParsedObject parsedObject = new ParsedObject();
                parsedObject.originalLine = line + "\n";
                parsedObject.firstNumber = Integer.valueOf(splitLine[0]);
                parsedObject.firstString = splitLine[1];
                parsedObject.secondNumber = Integer.valueOf(splitLine[2]);
                parsedObject.thirdNumber = Integer.valueOf(splitLine[3]);
                parsedObject.fourthNumber = Integer.valueOf(splitLine[4]);
                return parsedObject;
            }
    
            @Override
            public int compareTo(ParsedObject other) {
                return other.thirdNumber.compareTo(this.thirdNumber);
            }
        }
    }
    

    如果您还有任何问题,请随时提问 :) 这里是解析和排序后的示例对象列表。

    【讨论】:

      【解决方案3】:

      最简单的方法是首先创建一个类来保存文件中的数据,前提是您的行保持相同的格式

      public class MyClass {
      
        private Integer column1;
        private String column2;
        private Integer column3;
        private Integer column4;
        private Integer column5;
      
        public MyClass(String data) {
          String[] cols = data.split("-");
          if (cols.length != 5) return;
      
          column1 = Integer.parseInt(cols[0]);
          column2 = cols[1];
          column3 = Integer.parseInt(cols[2]);
          column4 = Integer.parseInt(cols[3]);
          column5 = Integer.parseInt(cols[4]);
        }
      
        public synchronized final Integer getColumn1() {
          return column1;
        }
      
        public synchronized final String getColumn2() {
          return column2;
        }
      
        public synchronized final Integer getColumn3() {
          return column3;
        }
      
        public synchronized final Integer getColumn4() {
          return column4;
        }
      
        public synchronized final Integer getColumn5() {
          return column5;
        }
      
        @Override
        public String toString() {
          return String.format("%d-%s-%d-%d-%d", column1, column2, column3, column4, column5);
        }
      }
      

      接下来,您可以像这样获取您的项目列表:

      public static List<MyClass> getLerRanking() throws IOException {
        List<MyClass> items = Files.readAllLines(Paths.get("jogadores.txt"))
          .stream()
          .filter(line -> !line.trim().isEmpty())
          .map(data -> new MyClass(data.trim()))
          .filter(data -> data.getColumn4() != null)
          .sorted((o1, o2) -> o2.getColumn4().compareTo(o1.getColumn4()))
          .collect(Collectors.toList());
      
        return items;
      }
      

      这将读取您的整个文件,过滤掉任何空白行,然后解析数据并将其转换为MyClass

      然后它会确保 column4 在转换后的对象中不为空。

      最后,它将根据第 4 列中的值对对象进行反向排序,并创建这些项目的列表。

      要打印结果,您可以这样做

      public static void main(String[] args) {
         List<MyClass> rankingList = getLerRanking();
         rankingList.forEach(item -> System.out.println(item));
      }
      

      由于我们覆盖了toString() 方法,它会在文件中显示对象时将其打印出来。

      希望这会有所帮助。

      【讨论】:

      • 感谢您的帮助,但是我没有完全理解您的代码,无法打印,我还在学习中,只是不想为我的游戏制作混乱的代码。跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      相关资源
      最近更新 更多