Java Map 集合的几种常用遍历方式
package com. zhong. mapdemo. map ;
import java. util. HashMap ;
import java. util. Map ;
import java. util. Set ;
public class MapFor {
public static void main ( String [ ] args) {
Map < String , Integer > hashMap = new HashMap < > ( ) ;
hashMap. put ( "鸡蛋" , 2 ) ;
hashMap. put ( "面条" , 10 ) ;
hashMap. put ( "抄手" , 12 ) ;
hashMap. put ( "饺子" , 14 ) ;
System . out. println ( hashMap) ;
System . out. println ( "-------------遍历全部的 key 根据 key 获取 value-------------" ) ;
for ( String key : hashMap. keySet ( ) ) {
Integer value = hashMap. get ( key) ;
System . out. println ( key + " ===> " + value) ;
}
System . out. println ( "-------------通过转换为 entrySet() 进行键值对遍历-------------" ) ;
for ( Map. Entry < String , Integer > kv : hashMap. entrySet ( ) ) {
System . out. printf ( "%s ===> " , kv. getKey ( ) ) ;
System . out. println ( kv. getValue ( ) ) ;
}
System . out. println ( "-------------lambda 遍历-------------" ) ;
hashMap. forEach ( ( k, v) -> System . out. println ( k + " ===> " + v) ) ;
}
}