美文网首页
java中的遍历一个hashMap的几种方式

java中的遍历一个hashMap的几种方式

作者: PENG先森_晓宇 | 来源:发表于2024-01-30 11:01 被阅读0次
class Study {
    public void rotate() {
        Map<String,String> res= new HashMap<>();
        res.put("a","b");
        res.put("c","d");

        //遍历所有key
        Set<String> keys = res.keySet();
        for (String key:keys){
            System.out.println("key为"+key);
        }

        //遍历所有value
        List<String> values = new ArrayList<>(res.values());
        for (String value:values){
            System.out.println("值为"+value);
        }

        //遍历所有key和value
        Set<Map.Entry<String,String>> entrys = res.entrySet();
        for (Map.Entry<String,String> entry:entrys){
            System.out.println("key为"+entry.getKey()+",value为"+entry.getValue());
        }

    }

    public static void main(String[] args) {
        Study study = new Study();
        study.rotate();
    }

}

相关文章

网友评论

      本文标题:java中的遍历一个hashMap的几种方式

      本文链接:https://www.haomeiwen.com/subject/btwnodtx.html