建立一个Map实例,k值为String类型,v值为Integer类型。依次用put方法输入如下:
map.put("Kobe", 24);
map.put("James", 6);
map.put("Durant", 35);
map.put("Anthony", 7);
现在要求打印出key为”Kobe“的v值(输出结果第一行),然后按照key值排序,利用迭代器输出结果。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class Main{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
HashMap<String,Integer>map = new HashMap<String,Integer>();
map.put("Kobe",24);
map.put("James",6);
map.put("Durant",35);
map.put("Anthony",7);
System.out.println(map.get("Kobe"));
Iterator<String> it = map.keySet().iterator();
TreeSet<String>tree = new TreeSet<String>();
while(it.hasNext()){
tree.add(it.next());
}
it = tree.iterator();
while(it.hasNext()){
String k = it.next();
Integer v = map.get(k);
System.out.println(k+"="+v);
}
}
}