Java Lab 17: More Collections
This lab uses Collections. Create a project named Lab17. Copy the classes and data file from Lab16. For the problems that re-write the search methods, you should comment out the old code, just in case, so things still work.
1. Create and new up three Map objects as HashMap's: byNameMap, byYearMap>, and byGenreMap >.
2. In the readMovies( ) method, along with populating the ArrayList of Movies, also populate byNameMap. The key is the Movie name and the value is the Movie. Do this in the same while loop. If there are duplicate names, just re-insert the movie – this will lose some data, but let's go with that.
3. Rewrite the searchByName( ) method to use byNameMap for the lookup instead of searching the movieList. create and return an ArrayList with just one movie, the one returned from byNameMap (so it doesn't break the other code). Test this to make sure it's working.
4. Again in readMovies( ), populate byYearMap, still in the same while loop. The key is the Movie year and the value is an ArrayList of Movie objects. Do the following steps:
- if the year is already in byYearMap, get its value – this is an ArrayList – and add the current Movie object to that
ArrayList. Because Maps return a reference to the ArrayList, you don't have to reinsert it (yep, it breaks encapsulation for the Map). In fact, see if you can do this in one line.
- if the year is not yet in byYearMap, create a new ArrayList, add the current Movie object to it, and insert this year and ArrayList into byYearMap.
5. Rewrite the searchByYear( ) method to use byYearMap for the lookup instead of searching the movieList. Ignore the MOVIE_COUNT limit –this time, return *all* of the movies for this year. Test this to make sure it's working.
6. One more time: in readMovies( ), in the while loop, populate byGenreMap. The key is the genre and the value is an ArrayList of Movie objects. Do this the same way you populated byYearMap, but with the following twist: write a for loop over the current movie's genres – remember, this is an ArrayList of genres. For each genre in that list, follow the
steps you used for byYearMap, but using the current genre.
7. Rewrite the searchByGenre( ) method to use byGenreMap for the lookup instead of searching the movieList. Ignore the MOVIE_COUNT limit –this time, return all the movies in this genre.
8. Write a method named displayTotals( ) that prints out the number of items in each data structure (movieList,
byNameMap, byYearMap, and byGenreMap). Call it in the main program, after the user chooses Quit. Here's the output of mine: