本文档用于汇总【java】中Map的使用方法:(持续更新)
一、Map的遍历:
1.1、Map的遍历方法
Map的遍历办法有多种,以下介绍几种常用的遍历方法:
1.1.1、使用Map.entrySet
//通过Map.entrySet遍历key和value
for(Map.Entry <String,String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
1.1.2、使用寄存器(iterator)
//通过Map.entrySet使用iterator遍历key和value
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
1.1.3、使用Map.keySet
//"通过Map.keySet遍历key和value
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
1.1.4、只遍历Value
//通过Map.values()遍历所有的value,但不能遍历key
for (String v : map.values()) {
System.out.println("value= " + v);
}
1.2、Map的遍历顺序
在上述1.1.1遍历方法中,如果遍历的Map声明为hashMap,则会发现,遍历时输出的元素顺序和之前加入Map的元素顺序不同。代码参考如下:
for(Map.Entry<String,String> entry : hashMap.entrySet()){
function(entry.getKey(),entry.getValue());
}
实例:
public static Map<Integer,String> switchstatuslist;
switchstatuslist=new HashMap<Integer,String>();
String switchlist;
for(Map.Entry<Integer,String> entry : switchstatuslist.entrySet()){
switchlist=switchlist+"{\"switchId\":\""+HexString.toHex(entry.getKey())+"\",\"switchstatus\":\""+entry.getValue()+"\"},";
}
原因是:HashMap散列图、Hashtable散列表是按“有利于随机查找的散列(hash)的顺序”存储元素,而并非按输入顺序存储。遍历时只能全部输出,而没有顺序。甚至可以rehash()重新散列,来获得更利于随机存取的内部顺序。
由此看来,Map的存储方式会影响到Map的遍历顺序。基本可以描述如下:
1.2.1、按元素输入顺序存储Map
如果将Map初试化为 java.util.LinkedHashMap
则该Map可以按元素输入顺序依次存储Map,在遍历该Map时可以获得和元素输入顺序相同的输出顺序。
public static Map<Integer,String> switchstatuslist;
switchstatuslist=new LinkedHashMap<Integer,String>();
1.2.2、按散列(hash)顺序存储Map
散列存储的优势是有利于随机查找,但是遍历Map不能按元素输入顺序获得输出。
public static Map<String,String> EntryflagMap;
EntryflagMap=new HashMap<String,String>();
类似的还有 java.util.LinkedHashSet