「Java」TreeMapの使い方
Javaコード
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String args[]) {
/* This is how to declare TreeMap */
TreeMap<Integer, String> tmap =
new TreeMap<Integer, String>();
/*Adding elements to TreeMap*/
tmap.put(1, “AA");
tmap.put(12, “BB");
tmap.put(30, “CC");
tmap.put(5, “DD");
tmap.put(3, “EE");
/* Display content using Iterator*/
@SuppressWarnings(“rawtypes")
Set set = tmap.entrySet();
@SuppressWarnings(“rawtypes")
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
@SuppressWarnings(“rawtypes")
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print(“key is: “+ mentry.getKey() + " & Value is: “);
System.out.println(mentry.getValue());
}
}
}
実行結果
key is: 1 & Value is: AA
key is: 3 & Value is: EE
key is: 5 & Value is: DD
key is: 12 & Value is: BB
key is: 30 & Value is: CC