-1

vehicles.csv

vehicleNo,type
1252,car
1234,motorbike
6543,car
2124,suv
5687,truck
4121,car

I have been given a csv file of this format. How should I go about counting the number of cars in this csv file.

kc9552
  • 25
  • 3
  • 10

2 Answers2

1

I'd stream the lines of the file, split each line to an array, filter out the cars and then parse the count and sum it:

long cars  = Files.lines(Paths.get("/path/to/vehicles.csv"))
                  .map(s -> s.split(","))
                  .filter(s -> s[1].equals("car"))
                  .mapToLong(s -> Long.parseLong(s[0]))
                  .sum();
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

The professional way would be to choose and leverage a CSV parsing thirdparty library, then use it to read the file, and loop through all entries, verifying if the entry is of a car and increment a counter if it is.

Or you could read through the file's lines with Files.lines(), and count the ones that end with ",car"

kumesana
  • 2,495
  • 1
  • 9
  • 10