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.
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();
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"