转载
/***
* Map类的一些简单操作
* 包括TreeMap的排序,HashMap的排序,四种遍历方式
* @author Administrator
*
*/
public class MapTest {
public static void main(String[] args) {
//创建map对象,并赋值
Map<String,String> treeMap = new TreeMap<String,String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
treeMap.put("sufow1", "舒泉1");
treeMap.put("sufow2", "舒泉2");
treeMap.put("sufow3", "舒泉3");
treeMap.put("sufow4", "舒泉4");
treeMap.put("sufow5", "舒泉5");
treeMap.put("sufow6", "舒泉6");
treeMap.put("sufow7", "舒泉7");
System.out.println("TreeMap");
//遍历map 方式一,根据keyset方法获取所有的key,再根据key获取值
for(String str :treeMap.keySet()){
String val = treeMap.get(str);
System.out.println(val);
}
Map<String,String> hashMap = new HashMap<String ,String>();
hashMap.put("sufow1", "舒泉1");//可以写入null值
hashMap.put("sufow2", "舒泉2");
hashMap.put("sufow3", "舒泉3");
hashMap.put("sufow4", "舒泉4");
hashMap.put("sufow5", "舒泉5");
hashMap.put("sufow6", "舒泉6");
hashMap.put("sufow7", "舒泉7");
System.out.println("HashMap");
//先排序
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(hashMap.entrySet());
//通过比较器来排序
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
//遍历List,第二种通过Map.Entry
for(Map.Entry<String, String> m :list){
String val = m.getValue();
System.out.println(val);
}
//第二种遍历map的方式,根据迭代器Iterator
Iterator<Map.Entry<String, String>> iterator = hashMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> map = iterator.next();
System.out.println(map.getKey());
System.out.println(map.getValue());
}
//第三种通过values,只能遍历value
for(String str:hashMap.values()){
System.out.println(str);
}
//第四种,通过Map.Entry
for(Map.Entry<String, String> map:hashMap.entrySet()){
System.out.println(map.getKey());
System.out.println(map.getValue());
}
}