导航:首页 > 编程语言 > pythonhashmap遍历

pythonhashmap遍历

发布时间:2022-05-11 10:35:13

㈠ 怎么遍历HashMap集合中的ArrayList集合对象

java">importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;

publicclassStudent
{
privateStringname;
privateintage;

publicStudent(Stringname,intage){
this.name=name;
this.age=age;
}

publicstaticvoidmain(String[]args)
{
for(Entry<String,List<Student>>e:prepare().entrySet()){
System.out.println(String.format("%s学生列表如下",e.getKey()));
for(Students:e.getValue()){
System.out.println(String.format("%s%d岁",s.name,s.age));
}
}
}
/**
*准备一组测试数据
*@return
*/
publicstaticMap<String,List<Student>>prepare(){
finalList<Student>studentList1=newArrayList<Student>(){
{
this.add(newStudent("张三",7));
this.add(newStudent("李四",6));
this.add(newStudent("王二",5));
}
};

finalList<Student>studentList2=newArrayList<Student>(){
{
this.add(newStudent("赵",10));
this.add(newStudent("钱",9));
this.add(newStudent("孙",8));
}
};
returnnewHashMap(){
{
this.put("一年级一班",studentList1);
this.put("一年级二班",studentList2);
}
};
}
}

写个简单的小例子,应该能看明白吧

打印结果

一年级二班学生列表如下
赵 10岁
钱 9岁
孙 8岁
一年级一班学生列表如下
张三 7岁
李四 6岁
王二 5岁

㈡ hashmap的遍历

方式1
Iterator iterator = hm.keySet().iterator();
while(iterator.hasNext()) {
System.out.println(hm.get(iterator.next()));
}
方式2
Set set = hm.entrySet() ;
java.util.Iterator it = hm.entrySet().iterator();
while(it.hasNext()){
java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
// entry.getKey() 返回与此项对应的键
// entry.getValue() 返回与此项对应的值
System.out.println(entry.getValue());
}

比较建议方式一的做法

㈢ 关于hashmap遍历问题

代码解释


```

` ````


// 一、第一种写法

HashMap hashMap = new HashMap();

for (Map.Entry en : hashMap.entrySet()) {


}

// 由于HashMap没加泛型,所以得到的Set也是没有泛型的

Set set = hashMap.entrySet();

// 由于Set没有泛型,程序不知道里面的元素是Map.Entry,这样写当然会报错

for (Map.Entry en : set) {


}

// 除非你这样写,将Set强转为Set<Map.Entry>,告诉代码Set里面的元素是Map.Entry

for (Map.Entry en : (Set<Map.Entry>) set) {


}


// 二、第二种写法

HashMap<String, String> hashMap2 = new HashMap();

// HashMap有泛型,因此调用entrySet()方法得到的Set也有泛型,泛型元素为Map.Entry

Set<Map.Entry<String, String>> entries = hashMap2.entrySet();

// 所以第二种写法循环不会报错

for (Map.Entry en : entries) {


}


` ````

```

㈣ 怎么遍历一个hashmap的键值对

for(Object obj:map.keySet()){
System.out.println(obj);
System.out.println(map.get(obj))
}

㈤ Hashmap遍历查询问题

首先,map中是不能存key 相同的值,如果key相同,则key对应的value为最后一次存的值;
然后,遍历map
Map root=new HashMap();
root.put("a", 1);
root.put("a", 100);
root.put("a", 2);
root.put("b", 3);
root.put("b", 44);
root.put("b", 5555);
root.put("c", 1111);
root.put("c", 9);
Iterator it=root.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, Integer> entry = (Entry<String, Integer>) it.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
最后,按照你这种想法,可以将hashmap 换成 arrayList;

㈥ 提供一个方法用于遍历获取HashMap<String,String>中所有value并存放在List中返回考虑上集合中泛型的使用

public List<String> getValueList(HashMap<String,String> map){
ArrayList<String> valueList = new ArrayList<>():
Collection<String> values = map.values();
for(String value : values){
valueList.add(value);
}
return valueList;
}

㈦ HashMap和List遍历方法总结及如何遍历删除

(一)List的遍历方法及如何实现遍历删除
我们造一个list出来,接下来用不同方法遍历删除,如下代码:
List<String> list= new ArrayList<String>();famous.add("zs");famous.add("ls");famous.add("ww");famous.add("dz");

1、for循环遍历list:
for(int i=0;i<list.size();i++){if(list.get(i).equals("ls"))list.remove(i);}

这是一种很常见的遍历方式,但是使用这种遍历删除元素会出现问题,原因在于删除某个元素后,list的大小发生了变化,而你的索引
也在变化,所以会导致你在遍历的时候漏掉某些元素。比如当你删除第一个元素后,继续根据索引访问第二个元素后,因为删除的原因,
后面的元素都往前移动了以为,所以实际访问的是第三个元素。因此,这种遍历方式可以用在读取元素,而不适合删除元素。
2、增强for循环:
for(String x:list){if(x.equals("ls"))list.remove(x);}

这也是一种很常见的遍历方式,但是使用这种遍历删除元素也会出现问题,运行时会报异常
其实增强for循环是java语法糖的一种体现,如果大家通过反编译得到字节码,那么上面这段代码的内部实现如下所示:

for(Iterator<String> it = list.iterator();it.hasNext();){String s = it.next();if(s.equals("madehua")){list.remove(s);}}

下面就解释为什么会报异常。分析Iterator的源代码,重点分析整个调用该过程中的
函数(hasNext和remove):

private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; // size为集合中元素的个数 } public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new (); cursor = i + 1; return (E) elementData[lastRet = i]; } /* 此方法并没被调用,只是调用List.remove方法 public void remove() { checkForComodification(); try { ArrayList.this.remove(lastRet); // size字段减1 cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new (); } } */ final void checkForComodification() { // 检查修改和当前版本号是否一致,不一致则抛出异常 if (modCount != expectedModCount) throw new (); } } // List.remove @Override public boolean remove(Object object) { Object[] a = array; int s = size; if (object != null) { for (int i = 0; i < s; i++) { if (object.equals(a[i])) { System.array(a, i + 1, a, i, --s - i); a[s] = null; // Prevent memory leak size = s; modCount++; // 核心代码:修改了版本号。这样当checkForComodification的时候,modCount值就和expectedModCount不同 return true; } } } else { for (int i = 0; i < s; i++) { if (a[i] == null) { System.array(a, i + 1, a, i, --s - i); a[s] = null; // Prevent memory leak size = s; modCount++; return true; } } } return false; }

接下来梳理一下流程,这时候你就会发现这个异常是在next方法的checkForComodification中抛出的。抛出的原因是
modCount !=expectedModCount。这里的modCount是指这个list对象从呢我出来到现在被修改的次数,当调用list
的add或者remove方法的时候,这个modCount都会自动增减;iterator创建的时候modCount被复制给了
expectedModcount,但是调用list的add和remove方法的时候不会同时自动增减expectedModcount,这样就导致
两个count不相等,从而抛出异常。大家如果理解了上面的执行流程,以后碰到类似这种问题,比如如果删除的是倒数
第二个元素却不会碰到异常。就会知道为什么了。

3、iterator遍历删除:

Iterator<String> it = list.iterator();while(it.hasNext()){String x = it.next();if(x.equals("del")){it.remove();}}

这种方式是可以正常遍历和删除的。但是你可能看到上面代码感觉和增强for循环内部实现的代码差不多,其实差别就在于上面使用
一个使用list.remove(),一个使用it.remove()。

(二)HashMap的遍历删除及如何实现遍历删除
一样我们先造一个hashmap出来,如下:

private static HashMap<Integer, String> map = new HashMap<Integer, String>();; public static void main(String[] args) { for(int i = 0; i < 10; i++){ map.put(i, "value" + i); } }

1、第一种遍历删除:

for(Map.Entry<Integer, String> entry : map.entrySet()){Integer key = entry.getKey();if(key % 2 == 0){System.out.println("To delete key " + key);map.remove(key);System.out.println("The key " + + key + " was deleted");}

这种遍历删除依旧会报异常,
2、第二种遍历删除:
Set<Integer> keySet = map.keySet(); for(Integer key : keySet){ if(key % 2 == 0){ System.out.println("To delete key " + key); keySet.remove(key); System.out.println("The key " + + key + " was deleted"); } }

这种遍历删除依旧会报异常,
3、第三种遍历删除:
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();while(it.hasNext()){Map.Entry<Integer, String> entry = it.next();Integer key = entry.getKey();if(key % 2 == 0){ System.out.println("To delete key " + key); it.remove(); System.out.println("The key " + + key + " was deleted");}}

这种遍历是OK的
分析上述原因,如果大家理解了List的遍历删除,那么感觉HashMap的遍历删除是不是有类似之处啊。下面就分析一下原因:
如果查询源代码以上的三种的删除方式都是通过调用HashMap.removeEntryForKey方法来实现删除key的操作。
在removeEntryForKey方法内知识一场了key modCount就会执行一次自增操作,此时modCount就与expectedModCOunt不一致了
,上面三种remove实现中,只有第三种iterator的remove方法在调用完removeEntryForKey方法后同步了expectedModCount值与
modCount相同,所以iterator方式不会抛出异常。最后希望大家遇到问题到查询源代码,它会给你最好的解释!

㈧ 使用python遍历文件夹将文件夹中所有的txt文本转为html连接形式。

importos
defgetalltxtfilename(path):
txtfilenames=[]
fordirpath,dirnames,filenamesinos.walk(path):
filenames=filter(lambdafilename:filename[-4:]=='.txt',filenames)
filenames=map(lambdafilename:os.path.join(dirpath,filename),filenames)
txtfilenames.extend(filenames)
returntxtfilenames
deftxttohtmllink(path):
filenames=getalltxtfilename(path)
htmllink=[]
forfilenameinfilenames:
ifos.path.isfile(filename):
htmllinktext=''
myfile=open(filename)
firstline=myfile.readline()
whilefirstlineandlen(firstline)<2:
firstline=myfile.readline()
ifnotfirstline:
firstline=''*2
else:
firstline=firstline.strip(' ')
htmllinktext+=firstline[0]+'<ahref="'+
filename+'">'+
firstline[1:]+'</a><br>'
htmllink.append(htmllinktext)
myfile.close()
returnhtmllink
path=r"文件夹路径"#将此处替换为实际文件夹的路径
htmllinks=txttohtmllink(path)
forhtmllinkinhtmllinks:
printhtmllink

在html标记前加上一个字符,这就不是合法的html文本形式,还是按照要求做了,如果输入到html文件肯定会出错

㈨ HashMap的几种遍历方式

有两种第一种: Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); } 效率高,以后一定要使用此种方式!第二种: Map map = new HashMap(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Object val = map.get(key); } 效率低,以后尽量少使用! HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: public class HashMapTest { public static void main(String[] args) ...{ HashMap hashmap = new HashMap(); for (int i = 0; i < 1000; i ) ...{ hashmap.put("" i, "thanks"); } long bs = Calendar.getInstance().getTimeInMillis(); Iterator iterator = hashmap.keySet().iterator(); while (iterator.hasNext()) ...{ System.out.print(hashmap.get(iterator.next())); } System.out.println(); System.out.println(Calendar.getInstance().getTimeInMillis() - bs); listHashMap(); } public static void listHashMap() ...{ java.util.HashMap hashmap = new java.util.HashMap(); for (int i = 0; i < 1000; i ) ...{ hashmap.put("" i, "thanks"); } long bs = Calendar.getInstance().getTimeInMillis(); java.util.Iterator it = hashmap.entrySet().iterator(); while (it.hasNext()) ...{ java.util.Map.Entry entry = (java.util.Map.Entry) it.next(); // entry.getKey() 返回与此项对应的键 // entry.getValue() 返回与此项对应的值 System.out.print(entry.getValue()); } System.out.println(); System.out.println(Calendar.getInstance().getTimeInMillis() - bs); } } 对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了。还是第一种好,简单。。。

㈩ HashMap 遍历问题

HashMap map2 = (HashMap) map1.get(it1);
改成
HashMap map2 = (HashMap) map1.get(str1);

对了给我加分

阅读全文

与pythonhashmap遍历相关的资料

热点内容
如何判断服务器有没有带宽 浏览:41
天正建筑批量删除命令 浏览:94
cad最下面的一排命令都什么意思 浏览:456
pythonimportcpp 浏览:850
W10的系统怎么给U盘加密 浏览:370
华为手机代码编程教学入门 浏览:762
和彩云没会员怎样解压 浏览:634
androidimageview保存 浏览:387
新买店铺什么服务器 浏览:883
文件夹能直接刻录吗 浏览:493
androidxmpp删除好友 浏览:969
javac哪个前景好 浏览:428
中华英才网app为什么不能搜索了 浏览:660
服务器域名是什么意思 浏览:52
Linux导出mysql命令 浏览:159
无诈建邺是什么app 浏览:228
python中的双色球 浏览:167
python解释器里如何换行 浏览:412
python编写格式 浏览:576
用python做出来的软件 浏览:469