You make a Booking
class that carries member variables such as length of the stay. Similar to what you show at the top of your code example. (Your getMostPopularRooms
method does not belong on this class. It should go elsewhere.)
You collect Booking
objects, apparently read from a CSV file according to your Question. Each row in the CSV is used to produce one Booking
object. Tip: Use a library such as Apache Commons CSV to assist with the chore of reading the CSV file. You will produce a List
or Set
of Booking
objects.
Instantiate a Map
to hold room names, for each of which you will store a number of days totaled across all the booking objects. Probably TreeMap
to keep the room names in order. From your Question, I deduce that you are tracking each room name using String
.
Tip: If you were to add the ThreeTen-Extra library to your project, you could use Days
type here instead of Integer
. For your homework assignment rather than real work, use Integer
.
For efficiency, you could set the initial capacity to the known number of rooms.
Map< String , Integer > roomPopularity = new TreeMap<>( numberOfRooms ) ;
Now loop your collection of Booking
objects. For each one, look up the matching key in the Map
. If not already present, add the key to map. Then retrieve the Integer
object for that room, and add that booking’s number of days to that number.
When finished, examine the values of the map to see which room is booked the most. This Question may help (not sure, didn't study).
All these pieces have been covered many times already on Stack Overflow. To learn more, search existing Questions and Answers.
You could probably use streams to good effect here. But as you are just starting with Java, use conventional syntax.
Your teacher may be intending for you to use simple arrays rather than collections. If so, the logic is similar. Create a pair of arrays, one for room name, and one for total days. As you read each CSV, look for the room name in the first array. If not found, add the room. Then look the same row number in the second array, for the number of days total. Add the incoming row's number of days to the total days. When done with the CSV, loop the elements of the total-days array, looking for the biggest number. Then bounce of to the array of array names to retrieve the name in the matching row.