我有一个SortedMap<String, SortedMap<String, Integer>>。其中每个字符串都是一个问题,并附有可能的答案和要点。
如何使用这个Map打印问题(第一个,第二个,.)像sampleArray[0]这样的职位
发布于 2014-05-25 17:57:46
遍历地图的一种方法是:
for (String aQuestion : myMap.keySet()) {
System.out.println(aQuestion)); //Prints each question.
System.out.println(myMap.get(aQuestion)); //Prints each answer using the same for loop
}或者,为了得到你可以做的答案:
myMap.values();这将获得一个包含所有值的集合,或者在您的情况下得到答案。集合有一个方法toArray(),它将返回一个普通数组以便于迭代。但是您也可以使用arraylist的addAll(Collection c)方法来创建数组列表。
List<String> myAnswers = new ArrayList<>();
myAnswers.addAll(myMap.values());发布于 2014-05-25 18:04:58
for (Entry<String, SortedMap<String, Integer>> q : test.entrySet()) {
System.out.println("Question=" + q.getKey());
for (Entry<String, Integer> a : q.getValue().entrySet()) {
System.out.println("Answer: " + a.getKey() + " for points " + a.getValue());
}
}或者如果你是java8
test.entrySet().stream().forEach((q) -> {
System.out.println("Question=" + q.getKey());
q.getValue().entrySet().stream().forEach((a) -> {
System.out.println("Answer: " + a.getKey() + " for points " + a.getValue());
});
});顺便说一句,在描述类型时,如果可能的话,可以使用接口/抽象类。
Map<String, Map<String, Integer>> test;不
SortedMap<String, SortedMap<String, Integer>> test;发布于 2014-05-25 17:55:55
就像通常的映射一样,您可以在键集上迭代:
SortedMap<String, SortedMap<String, Integer>> questions;
//some processing
for (String question : questions.keySet()) {
System.out.println(question);
}https://stackoverflow.com/questions/23858238
复制相似问题