通过一个复杂的数据结构,一个HasMap



我有一个HashMap,看起来像:

( student1 => Map( name => Tim,         
                   Scores => Map( math => 10,
                                  physics => 20,
                                  Computers => 30),
                    place => Miami,
                    ranking => Array(2,8,1,13),
                  ),
  student2 => Map ( 
                   ...............
                   ...............
                ),
   ............................
   ............................
);

由于键不是任何特定类型(对象,字符串,整数等),我如何"潜水"通过这个复杂的哈希图?

编辑:"潜水"意味着遍历每个键和值。

怎么样

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
}

像智慧一样

完全未经测试,不能保证适合任何目的(你的问题有些模糊),但它应该让你知道如何处理你的问题:

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());
  }
}

使用类似的东西

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));
    }
  }
}

最新更新