我有一个HashMap,它看起来像:
( student1 => Map( name => Tim,
Scores => Map( math => 10,
physics => 20,
Computers => 30),
place => Miami,
ranking => Array(2,8,1,13),
),
student2 => Map (
...............
...............
),
............................
............................
);
由于键不是任何特定类型(对象,字符串,整数等),我如何“潜入”这个复杂的HashMap?
编辑:“潜水”意味着遍历每个键和值。
答案 0 :(得分:3)
怎么样
Map<Long, Student> studentIdToStudentMap = new HashMap<Long, Student>();
和
class Student{
private String name;
private List<Score> scores;
private Location location;
private List<Rank> rankings;
//const, equals(), hashcode(), accessors
}
和
class Score{
private String subject;
private float marksObtained;
private float totalMark;
private Long examId;
//const, equals(), hashcode(), accessors
}
同样聪明
答案 1 :(得分:1)
完全未经测试且无法保证适合任何目的(您的问题有些模糊),但它应该让您了解如何处理您的问题:
public void doStuffWithMap(Map yourMap)
{
for(Map.Entry entry : yourMap.entrySet())
{
if (entry.getValue() instanceof Map)
doStuffWithMap((Map)entry.getValue());
else
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
答案 2 :(得分:1)
使用类似
的内容private static printKeyValues(Map map) {
for (Object key : map.keySet()) {
if(map.get(key) instanceOf Map) {
printKeyValues((Map)map.get(key))
} else {
System.out.println("key:" + key+" value:"+ map.get(key));
}
}
}