1. When you wrote the FindareaCode program for the preceding exercise, it is lik
ID: 3600513 • Letter: 1
Question
1. When you wrote the FindareaCode program for the preceding exercise, it is likely that you generated the list of area codes for a state by looping through the entire map and printing any area codes that mapped to that state. Although this strategy is fine for small maps like the area code example, efficiency becomes an issue in working with much larger data maps. An alternative approach is to invert the map so that you can perform lookup operations in either direction. You can't, however, declare the inverted map as a Map, because there is often more than one area code associated with a state. What you need to do instead is to make the inverted map a Map that maps each state name to a vectorExplanation / Answer
Please find my implementation.
Please let me know in case of any issue.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
public class FinaAreaCode {
public static void main(String[] args) throws IOException {
// creating inverted map
Map<String, Vector<Integer>> invertedMap = new HashMap<String, Vector<Integer>>();
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String[] arr = line.split("\s+");
String key = arr[0].trim().toLowerCase();
if(invertedMap.containsKey(key)) {
Vector<Integer> vec = invertedMap.get(key);
vec.add(Integer.parseInt(arr[1].trim()));
invertedMap.put(key, vec);
}else{
Vector<Integer> vec = new Vector<>();
vec.add(Integer.parseInt(arr[1].trim()));
invertedMap.put(key, vec);
}
}
br.close();
fr.close();
// printing map
for(Map.Entry<String, Vector<Integer>> entry : invertedMap.entrySet()) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
/*
// data.txt format
xyz 234
uyt 456
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.