如何从Java的CSV文件中获取最大值和最小值

时间:2019-03-13 14:40:06

标签: java loops csv while-loop

这是我的CSV文件:marks.csv,其中包含学生编号(左侧)和右侧的标记:

B00123,55
B00783,35
B00898,67

我需要能够搜索该文件并找到最大标记和最小标记。我有这段返回值的代码,但之后我不知道该怎么做:

public static void MaxAndMin()
{
  // .csv files are comma separated
  String fileName = "src\\data\\marks.csv";
  File file = new File(fileName);

  try 
  {
      Scanner inputStream = new Scanner(file);

      while(inputStream.hasNext())
      {
          String data = inputStream.next();
          String [] values = data.split(",");
          int mark = Integer.parseInt(values[1]);
          System.out.println(mark);      
      }

      inputStream.close();

  } 
  catch (FileNotFoundException ex) 
  {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  }
}

这将返回以下内容:

 55
 35
 67

不知道下一步该怎么做,任何帮助不胜感激!谢谢!

4 个答案:

答案 0 :(得分:2)

对此的更简短,更清晰,更简洁的回答可能是:

private static void minAndMax() {
    try (Stream<String> stream = Files.lines(Paths.get(FILE_PATH))) {
        IntSummaryStatistics statistics = stream
            .map(s -> s.split(",")[1])
            .mapToInt(Integer::valueOf)
            .summaryStatistics();
        System.out.println("Lowest:: " + statistics.getMin());
        System.out.println("Highest:: " + statistics.getMax());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

只需读取文件的行,打开一个Stream<String>,在逗号上映射并拆分它,映射到Integer并从中创建一个IntSummaryStatistics对象。然后只需使用getMingetMax值。干净简单。还请注意,此答案使用try-with-resources自动管理可能需要手动处理的各种操作。

答案 1 :(得分:1)

public static void MaxAndMin()
                {
                    // .csv files are comma separated
                    String fileName = "src\\data\\marks.csv";
                    File file = new File(fileName);
                    TreeSet<Integer> ts1 = new TreeSet<Integer>(); 
                    try 
                    {
                        Scanner inputStream = new Scanner(file);

                        while(inputStream.hasNext())
                        {
                            String data = inputStream.next();
                            String [] values = data.split(",");
                            int mark = Integer.parseInt(values[1]);
                            ts1.add(mark);     
                        }


                        inputStream.close();

                        System.out.println("Min Marks"+ts1.first());
                        System.out.println("Max Marks"+ts1.last());
                    } 
                    catch (FileNotFoundException ex) 
                    {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

您可以将值存储在Treeset中,然后获取第一个和最后一个元素。 树集按排序顺序存储元素。

答案 2 :(得分:0)

通过阅读文件的各行并用分隔符(在您的区域设置中用逗号分隔)将每一行分开,您将走在正确的轨道上。

为了找到最大值,您有几种可能。一个简单的类就是一个类属性,假设private int maxValue = -1;可以用来在循环中存储当前的最大值。检查maxValue是否小于当前值(代码中的mark),如果是,则设置maxValue = mark;

例如,您可以将所有值存储在图元和String的数据结构中,或者使对象成为适当的自定义类,然后将它们存储在List中。然后,随后迭代该结构或使用最新的流API。一个小例子是这样:

public static void main(String[] args) {
    // use java.nio to access the file system object
    Path csvPath = Paths.get("U:\\temp\\stackoverflow\\some_file.csv");
    // create a data structure that stores the values read from csv file
    Map<String, Integer> lineValues = new HashMap<String, Integer>();
    try {
        // read the file content (this does not take care of a header line!)
        List<String> lines = Files.readAllLines(csvPath, StandardCharsets.ISO_8859_1);
        // split each line into the values  
        lines.forEach(line -> {
            String[] values = line.split(",");
            // put the values into the data structure
            lineValues.put(values[0], Integer.parseInt(values[1]));
        });

        // use the stream api to get the maximum value from the data structure
        int max = lineValues.values().stream().max(Integer::compareTo).get();
        // print the result
        System.out.println("The maximum value in " + csvPath.toAbsolutePath().toString() + " is " + max);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

答案 3 :(得分:0)

您可以执行以下操作,请记住,我使用Java 8中的Integers流从List中查找最小值和最大值:

    public static void maxAndMin() {
    // .csv files are comma separated
    String fileName = "src\\data\\marks.csv";
    File file = new File(fileName);

    try(Scanner inputStream = new Scanner(file)) {
        ArrayList<Integer> listNumbers = new ArrayList<>();

        while(inputStream.hasNext()) {
            String data = inputStream.next();
            listNumbers.add(Integer.valueOf(data.split(",")[1]));
        }

        int maxValue = listNumbers.stream().max(Comparator.comparing(Integer::valueOf)).get();
        int minValue = listNumbers.stream().min(Comparator.comparing(Integer::valueOf)).get();

        System.out.println("Max value is : "+maxValue);
        System.out.println("Min value is : "+minValue);
    }
    catch (FileNotFoundException ex)
    {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}