1、foreach 循环(推荐使用)
取key 或 value 时使用 Java5以后引用 需要判空,否则会抛异常
Map < ? , Object > map = new HashMap < String , Object > ( ) ;
for ( Map. Entry < ? , Object > entry : map . entrySet ( ) ) {
System . out. println ( entry. getKey ( ) ) ;
System . out. println ( entry. getValue ( ) ) ;
}
2、foreach 循环(单独key或者单独value)
Map < ? , Object > map = new HashMap < String , Object > ( ) ;
for ( String key: map. keySet ( ) ) {
System . out. println ( "Key = " + key) ;
}
for ( Object key: map. values ( ) ) {
System . out. println ( "Value = " + value) ;
3、Iterator迭代
Map < String , Object > map = new HashMap < String , Object > ( ) ;
Iterator < Map. Entry < String , Object > > entries = map. entrySet ( ) . iterator ( ) ;
while ( entries. hasNext ( ) ) {
Map. Entry < ? , Object > entry = entries. next ( ) ;
System . out. println ( entry. getKey ( ) ) ;
System . out. println ( entry. getValue ( ) ) ;
}
Map map = new HashMap ( ) ;
Iterator entries = map. entrySet ( ) . iterator ( ) ;
while ( entries. hasNext ( ) ) {
Map. Entry entry = ( Map. Entry ) entries. next ( ) ;
String key = ( String ) entry. getKey ( ) ;
Object value = ( Object ) entry. getValue ( ) ;
System . out. println ( String ) ;
System . out. println ( Object ) ;
}
4、迭代keys并搜索values(不推荐、效率低)
Map < String , Object > map = new HashMap < String , Object > ( ) ;
for ( String key : map. keySet ( ) ) {
Object value = map. get ( key) ;
System . out. println ( key) ;
System . out. println ( value) ;
}