java中HashMap遍历方法

时间:2021-12-08 15:50:55

在开发过程中,往往都要用到HashMap来存储数据,如何对HashMap进行遍历,今天在做项目过程中正好用到,所以写下来供大家参考。对HashMap遍历建议使用Collection类的Iterator,此类提供的方法可以方便的遍历Vector, ArrayList, LinkedList等集合元素。

1.hasNext()函数的API解释

boolean java.util.Iterator.hasNext()
boolean hasNext()

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

Returns:
true if the iteration has more elements

2、next()函数的API解释

Object java.util.Iterator.next()
Returns the next element in the iteration.

Returns:the next element in the iteration

3、代码

package list.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ListTest {
public static HashMap<String, List<Object>> mHashMap = new HashMap<String,List<Object>>();
public static String str = "123456:78915:17896";

public static void main(String[] args){
initHashMap();
}
/*****
* 对HashMap赋值
*/

public static void initHashMap(){
List<Object> mList = new ArrayList<Object>();
mList.add("qcs"+1);
mList.add("qcs"+2);
mList.add("qcs"+3);
mHashMap.put("1", mList);

List<Object> mList2 = new ArrayList<Object>();
mList2.add("jsjqcs"+1);
mList2.add("jsjqcs"+2);
mList2.add("jsjqcs"+3);
mHashMap.put("2", mList2);

List<Object> mList3 = new ArrayList<Object>();
mList3.addAll(spliteFilename(str));
mHashMap.put("3", mList3);
}
/****
* 判断key对应的值是否存在HashMap中
* @param values
* @return
*/

public boolean isExit(String key){
if(mHashMap.containsKey(key)){
return true;
}
return false;
}
/*****
* 获取HashMap中对应的key值
* @param key
*/

@SuppressWarnings("unchecked")
public void getHashMapValues(String key){
Iterator<?> iter = mHashMap.entrySet().iterator();
while(iter.hasNext()){
Map.Entry entry = (Map.Entry)iter.next();
String mstr = (String)entry.getKey(); //获取HashMap的key
if(mstr.equals(key)){
List<Object> list = (List<Object>)entry.getValue();//获取HashMap的key对应的值
for(int i=0;i<list.size();i++)
System.out.println(list.get(i).toString()); //输出该HashMap中key对应的值
}
}
}
/***
* 对字符串进行分割
* @param piclist
* @return
*/

public static List<Object> spliteFilename(String piclist) {
// TODO Auto-generated method stub
List<Object> list = new ArrayList<Object>();
String childStr[] = piclist.toString().split(":");
for(int i=0;i<childStr.length;i++){
list.add(childStr[i]);
System.out.println(childStr[i]);
}
return list;
}
}