Reputation: 869
I have a set of 3 nested TreeMaps:
TreeMap<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>> keyDay = new TreeMap<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>>();
TreeMap<Court, TreeMap<Time, String>> keyCourt = new TreeMap<Court, TreeMap<Time, String>>();
TreeMap<Time, String> keyTime = new TreeMap<Time, String>();
which store info for bookings. I'm trying to iterate through them using nested while loops to show all the bookings that have been created, but I need a way in the nested whiles to show only the values which relate to the relevant parent.
Here's what I have:
Iterator listOfDays = keyDay.keySet().iterator();
Iterator listOfCourts = keyCourt.keySet().iterator();
Iterator listOfTimes = keyTime.keySet().iterator();
String output;
while (listOfDays.hasNext()) {
DayOfWeek currentDay = (DayOfWeek) (listOfDays.next());
output += currentDay.toString() + "\n----------\n";
while (listOfCourts.hasNext()){
Court currentCourt = (Court) (listOfCourts.next());
output += currentCourt.toString() + ":\n";
while (listOfTimes.hasNext()){
Time currentTime = (Time) (listOfTimes.next());
String currentName = (String) keyTime.get(currentTime);
output += currentTime.toString() + " - " + currentName + "\n";
}
}
...but as expected (but not wanted), it just iterates through all the entries in each TreeMap til the end.
Can anyone help?
Upvotes: 1
Views: 2901
Reputation: 691745
It's not very clear (what are listOfDays, listOfCourts and listOfTimes?), but I guess you need something like this:
for (Map.Entry<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>> dayEntry : keyDay.entrySet()) {
DayOfWeek currentDay = dayEntry.getKey();
output += currentDay.toString() + "\n----------\n";
for (Map.Entry<Court, TreeMap<Time, String>> courtEntry : dayEntry.getValue().entrySet()) {
Court currentCourt = courtEntry.getKey();
output += currentCourt.toString() + ":\n";
for (Map.Entry<Time, String> timeEntry : currentCourt.getValue().entrySet()) {
Time currentTime = timeEntry.getKey();
String currentName = timeEntry.getValue();
output += currentTime.toString() + " - " + currentName + "\n";
}
}
}
In short, a map can be viewed as a set of map entries, and you can iterate through this entry set. Each entry has a key and a value. Since the value, in your case, is another map, you can repeat this operation on the value.
Upvotes: 3