今回は簡単な所で、TreeMapをJava 1.5から導入された拡張for文でループする方法。割とIteratorを使って解説してるサイトが多いな、と思ったので。
Map<String, Integer> treeMap = new TreeMap<String, Integer>();
treeMap.put("M00000005", 5);
treeMap.put("M00000004", 4);
treeMap.put("M00000007", 7);
treeMap.put("M00000002", 2);
treeMap.put("M00000010", 10);
treeMap.put("M00000006", 6);
treeMap.put("M00000008", 8);
treeMap.put("M00000009", 9);
treeMap.put("M00000003", 3);
treeMap.put("M00000001", 1);
for (String key : treeMap.keySet()) {
  System.out.println("Value -> " + treeMap.get(key));
}
こんな感じ。もし、Mapのキーじゃなくて、Map自体が欲しければ、こんな感じ。
for (Map.Entry<String, Integer> map : treeMap.entrySet()) {
  System.out.println("Value -> " + map.getValue());
}
Collectionsを全部ループするのに、拡張for文はシンプルに書けるので、最近愛用してる。この方法で、他のMapも取れるはず。 
 


0 コメント:
コメントを投稿