Consider this class: 1. Write a method called buildIndex that takes an ArrayList
ID: 3767614 • Letter: C
Question
Consider this class:
1. Write a method called buildIndex that takes an ArrayList of person objects and constructs a map from strings (the person's name) to person objects, just like a phone book. The kind of loop you use is up to you.
2. Consider the Person class from the previous question. Write a method called reverseIndex that takes a Map<String, Person> as a parameter. It's parameter is a mapping from names to person objects, just like the phone book map returned by buildIndex in the previous question. From this parameter, construct a new map that represents a "reverse-lookup phone book, that allows you to look up phone numbers and find out who they belong to. In other words, reverseIndex should return a new map from strings to person objects that contains all the original person objects in the original map, but now using phone numbers as the keys instead of names.
3. Write a method called printToN that takes an integer as a parameter and prints out the numbers from N to 1 (decreasing order), each number on a separate line. Use a numeric for loop.
4. Write a method called mapToList that takes a map from strings to Person objects as a parameter and returns a new ArrayList of Person objects containing all of the values from the map.
Explanation / Answer
Map<String, Person> buildIndex(ArrayList<Person> p){
Map<String, Person> m = new HashMap<String, Person>();
for(int i = 0; i < p.size(); i++){
m.put(p.get(i).name, p.get(i));
}
return m;
}
Map<String, Person> reverseIndex(Map<String, Person> p){
Map<String, Person> m = new HashMap<String, Person>();
for(int i = 0; i < p.size(); i++){
m.put(p.get(i).number, p.get(i));
}
return m;
}
void printToN(int n){
for(int i = n; i >= 1; i--){
System.out.println(i);
}
}
ArrayList<Person> mapToList(Map<String, Person> p){
ArrayList<Person> m = new ArrayList<Person>();
for(int i = 0; i < p.size(); i++){
m.add(p.get(i));
}
return m;
}