简体   繁体   中英

How to get Max and Min values from CSV file in Java

Here is my CSV file: marks.csv and it contains with the student number on the left and the marks on the right:

B00123,55
B00783,35
B00898,67

I need to be able to search through this file and find the maximum mark and the minimum mark. I have this code that returns the values but I don't know what to do afterwards:

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);
  }
}

And this returns the following:

 55
 35
 67

What can I try next?

A shorter, clearer and less verbose answer to this could be the following:

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();
    }
}

Simply read the file's lines, open up a Stream<String> , map and split it on the comma, map to an Integer and create an IntSummaryStatistics object out of it. Then simply use the getMin and getMax values. Clean and simple. Note also that this answer uses try-with-resources to auto manager the various actions that may require manual handling.

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);
                    }
                }

You can store values in Treeset and then fetch first and last element. Treeset stores element in sorted order.

You are on the right track by reading the lines of the file and splitting each line by the separator (comma in your locale).

In order to find the maximum value, you have several possibilities. A simple one would be a class attribute, let's say private int maxValue = -1; which you can use to store the current maximum in your loop. Check if maxValue is less than the current value ( mark in your code) and if yes, set maxValue = mark; .

You can alternatively store all the values in a data structure for primitives and String s or make objects of a proper custom class and store those in a List , for example. Then iterate the structure afterwards or use the up-to-date stream API. A small example is this:

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();
    }
}

You can do something like this, keep in mind that I used streams of Integers in Java 8 to find the min and max from 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);
    }
}

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