我有一组3个嵌套的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>();
存储预订信息。我正在尝试使用嵌套的while循环遍历它们以显示已创建的所有预订,但我需要在嵌套的while中使用一种方法来仅显示与相关父级相关的值。
这就是我所拥有的:
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";
}
}
...但是正如预期的那样(但不是想要的),它只是迭代每个TreeMap中的所有条目直到结束。
有人可以帮忙吗?
答案 0 :(得分:3)
目前还不是很清楚(listOfDays,listOfCourts和listOfTimes是什么?),但我想你需要这样的东西:
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";
}
}
}
简而言之,可以将地图视为一组地图条目,您可以遍历此条目集。每个条目都有一个键和一个值。由于该值(在您的情况下)是另一个映射,因此您可以对值重复此操作。