This is a beta version of Practice-It. Give us feedback

logo Practice-It logo

byAge

Language/Type: Java Collections Sets and Maps
Author: Marty Stepp (on 2018/05/01)

Write a method byAge that accepts three parameters: 1) a Map where each key is a person's name (a string) and the associated value is that person's age (an integer); 2) an integer for a minimum age; and 3) an integer for a maximum age. Your method should return a new Map with information about people with ages between the min and max, inclusive.

In your result map, each key is an integer age, and the value for that key is a string with the names of all people at that age, separated by "and" if there is more than one person of that age. Your result map's pairs should be sorted in ascending order by age (keys). Include only ages between the min and max inclusive, where there is at least one person of that age in the original map. If the map passed is empty, or if there are no people in the map between the min/max ages, return an empty map.

For example, if a Map named ages stores the following key=value pairs:

{Paul=28, David=20, Janette=18, Marty=35, Stuart=98, Jessica=35, Helene=40, 
 Allison=18, Sara=15, Grace=25, Zack=20, Galen=15, Erik=20, Tyler=6, Benson=48}

The call of byAge(ages, 16, 25) should return the following map (the contents can be in any order):

{18=Janette and Allison, 20=David and Zack and Erik, 25=Grace}

For the same map, the call of byAge(ages, 20, 40) should return the following map:

{20=David and Zack and Erik, 25=Grace, 28=Paul, 35=Marty and Jessica, 40=Helene}

Obey the following restrictions in your solution:

  • You will need to construct a map to store your results, but you may not use any other structures (arrays, lists, etc.) as auxiliary storage. (You can have as many simple variables as you like.)
  • You should not modify the contents of the map passed to your method.
  • Your solution should run in no worse than O(N log N) time, where N is the number of pairs in the map.
Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.