-2

我有一个 HashMap,它看起来像:

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

由于键不是任何特定类型(对象、字符串、整数等),我如何“潜入”这个复杂的 HashMap ?

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

4

3 回答 3

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
}

同样地

于 2012-06-13T05:01:08.357 回答
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());
  }
}
于 2012-06-13T05:05:04.490 回答
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));
    }
  }
}
于 2012-06-13T05:05:29.583 回答