作者:小菜鸡 | 来源:互联网 | 2023-01-16 12:05
在开发过程中,往往都要用到HashMap来存储数据,如何对HashMap进行遍历,今天在做项目过程中正好用到,所以写下来供大家参考。对HashMap遍历建议使用Collection类的
在开发过程中,往往都要用到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 mHashMap = new HashMap();
public static String str = "123456:78915:17896";
public static void main(String[] args){
initHashMap();
}
/*****
* 对HashMap赋值
*/
public static void initHashMap(){
List mList = new ArrayList();
mList.add("qcs"+1);
mList.add("qcs"+2);
mList.add("qcs"+3);
mHashMap.put("1", mList);
List mList2 = new ArrayList();
mList2.add("jsjqcs"+1);
mList2.add("jsjqcs"+2);
mList2.add("jsjqcs"+3);
mHashMap.put("2", mList2);
List mList3 = new ArrayList();
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();
if(mstr.equals(key)){
List list = (List)entry.getValue();
for(int i=0;i System.out.println(list.get(i).toString());
}
}
}
/***
* 对字符串进行分割
* @param piclist
* @return
*/
public static List spliteFilename(String piclist) {
List list = new ArrayList();
String childStr[] = piclist.toString().split(":");
for(int i=0;i list.add(childStr[i]);
System.out.println(childStr[i]);
}
return list;
}
}