简体   繁体   中英

Parsing CSV File in Java

I'm a Java Beginner. I have a CSV file in the format (City;Gender;Age). eg how can I count how many males , age < 40 live in a certain city. Any Suggestions?

public void method() throws IOException {
     int count = 0;
     FileReader fr = new FileReader(file);
     BufferedReader br = new BufferedReader(fr);
     String line;
     while((line = br.readLine())!= null){
         br.readLine();
         String [] l = line.split(";");
          if(l[0].equals("CityA")&&l[1].equals("M")&&l[2].equals("<40")) {
              count++;
          }    
      }
}

Can be done with streamAPI:

long count = Files.lines(Paths.get(PATH_TO_CSV))
            .map(s -> s.split(";"))
            .filter(arr -> arr[0].equals("CityA"))
            .filter(arr -> arr[1].equals("M"))
            .filter(arr -> Integer.parseInt(arr[2]) < 40)
            .count();

System.out.println(count);

You are trying to do "string".equals("<40") which is checking if the string "string" is equivalent to the string "<40" , not if that value is less than 40.

Try converting the string at l[2] to an integer, and then doing the check:

int age = Integer.parseInt(l[2]);
if (l[0].equals("CityA") && l[1].equals("M") && age < 40) {
    count++;
}

If you have line = br.readline() at the beginning of the while, you don't need the second statement br.readline(); inside the while as well. Are you not getting the correct answer? Are you trying to improve code style?

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