8000 add a method to read in csv file and count · fishercoder1534/RandomJava@9831290 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9831290

Browse files
add a method to read in csv file and count
1 parent 126bee2 commit 9831290

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/main/java/IO_example/JavaFileIOExample.java

Lines changed: 21 additions & 0 deletions
8000
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import java.io.File;
44
import java.io.IOException;
5+
import java.util.HashMap;
6+
import java.util.Map;
57
import java.util.Scanner;
68

79
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -11,6 +13,7 @@ public class JavaFileIOExample {
1113
public static void main(String... args) throws IOException {
1214
System.out.println("Program started.");
1315
readFileOnDisk();
16+
findUniqueCityNames();
1417
System.out.println("Program finished.");
1518
}
1619

@@ -26,4 +29,22 @@ private static void readFileOnDisk() throws IOException {
2629

2730
scanner.close();
2831
}
32+
33+
private static void findUniqueCityNames() throws IOException {
34+
String file = "src/test/resources/city_names.csv";
35+
Scanner scanner = new Scanner(new File(file));
36+
scanner.useDelimiter(",");
37+
Map<String, Integer> map = new HashMap<>();
38+
while (scanner.hasNext()) {
39+
String city = scanner.next();
40+
map.put(city, map.getOrDefault(city, 0) + 1);
41+
}
42+
scanner.close();
43+
System.out.println("Unique city names are: ");
44+
for (String city : map.keySet()) {
45+
if (map.get(city) == 1) {
46+
System.out.println(city);
47+
}
48+
}
49+
}
2950
}

src/test/resources/city_names.csv

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
NYC,NYC,NYC,Cedar Park,NYC,NYC,NYC,NYC,San Jose,San Jose,San Jose,San Jose,McKinney,San Jose,SF,LA,LA,LA,LA,LA,San Diego,San Diego,San Diego,Seattle,Portland,Portland,Portland,Boston,D.C,D.C,D.C,Miami,Dallas,Cedar Park,McKinney,Melissa,Sacramento,Sacramento

0 commit comments

Comments
 (0)
0