-
键值对形式
-
增删查改
public class TestMap {
public TestMap()
Map<String, String> map = new HashMap<String, String>();
map.size();
//在添加时,key重复,相当于值的修改
map.put("key1", "value1");
System.out.println(map.size());
map.get("key1");
map.remove("key1");
map.clear();
/*
* 删除操作,使用key值
* 没有对应的key,返回空
* 如果有,返回被删除的值
*/
/*
* /key+value执行删除
* 匹配,返回true
* 没有,返回false
*/
//如果键对应为空,删除之前应先判断
//map("key",null);
}
}
遍历
map.put("key1", "value1");
map.put("key2", "value2");
for (Object key : map.keySet()) {
System.out.println(key + " :" + map.get(key));
}
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " :" + entry.getValue());
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " :" + map.get(key));
}
Iterator<Map.Entry<String, String>> iterator1 = map.entrySet().iterator();
while (iterator1.hasNext()) {
Map.Entry<String, String> entry = iterator1.next();
System.out.println(entry.getKey() + " :" + entry.getValue());
}
排序
public void sort() {
//推荐排序
Map<String, String> map = new HashMap<String, String>();
map.put("a", "c");
map.put("b", "b");
map.put("c", "a");
// 通过ArrayList构造函数把map.entrySet()转换成list
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
// 通过比较器实现比较排序
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
return mapping1.getKey().compareTo(mapping2.getKey());
}
});
for (Map.Entry<String, String> mapping : list) {
System.out.println(mapping.getKey() + " :" + mapping.getValue());
}
}