Map集合遍历方式(三种keySet、entrySet、forEach)

package Maptest01;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * FileName: MapDemo02
 * Author:   lps
 * Date:     2022/4/14 11:59
 * Sign:刘品水 Q:1944900433
 */
public class MapDemo02 {
    public static void main(String[] args) {
        Map<String, Integer> maps = new HashMap<>();//一行经典代码
        maps.put("刘品水",3);
        maps.put("枸杞",13);
        maps.put("Java",1);
        maps.put("Java",100);
        maps.put("手机",50);


        Set<String> keys = maps.keySet();
        for (String key : keys) {
            Integer value = maps.get(key);
            System.out.println(key+"====>"+value);
        }
        System.out.println("===========");
        Set<Map.Entry<String, Integer>> entries = maps.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            System.out.println(entry.getKey()+"===>"+entry.getValue());
        }

        System.out.println("========");
        //default void forEach(BiConsumer<? super K,? super V> action) 对此映射中的每个条目执行给定的操作,直到所有条目都被处理或操作引发异常。  
        maps.forEach((key, value) -> System.out.println(key+","+value));
        //  maps.forEach(new BiConsumer<String, Integer>() {
        //            @Override
        //            public void accept(String key, Integer value) {
        //                System.out.println(key+","+value);
        //            }
        //        });

    }
}

 

posted @ 2022-04-15 11:07  刘品水  阅读(362)  评论(0编辑  收藏  举报