K-Mei
K-Mei

Reputation: 13

Parsing CSV File in Java

I'm a Java Beginner. I have a CSV file in the format (City;Gender;Age). e.g 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++;
          }    
      }
}

Upvotes: 0

Views: 99

Answers (3)

ladyskynet
ladyskynet

Reputation: 327

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?

Upvotes: 0

Matt
Matt

Reputation: 1122

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

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

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

Upvotes: 1

Related Questions