In Java (3) (20 pts) Here\'s an example of a situation that\'s well-suited for u
ID: 3713955 • Letter: I
Question
In Java
(3) (20 pts) Here's an example of a situation that's well-suited for using the map data structure. Suppose you have a data file of students at a university, and you're trying to figure out how many students are in each major. You can read the file and parse the information into a map, where the keys are the majors and the values are the counts of how many students are in that major. Write a method countMajors(String filename) that reads the data in filename and returns a Map as described above. Feel free to use the built-in Java map classes (java.util.HashMap, ava.util.TreeMap) in your solution. You can assume that each line of the data file is formatted like this: lastname,firstname,major A small sample data file is provided on eCourseware that you can use to help test your code. However, your method should work for any file formatted the same way!Explanation / Answer
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class CountMajor {
public static Map<String, Integer> countMajors(String filename) throws IOException {
Map<String, Integer> majorsMap = new HashMap<>();
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while((line = bufferedReader.readLine()) != null) {
String[] parts = line.split(",");
String major = parts[2];
Integer count = majorsMap.get(major);
majorsMap.put(major, count == null ? 1 : count + 1);
}
bufferedReader.close();
return majorsMap;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.