美文网首页
HashMap的七种循环遍历

HashMap的七种循环遍历

作者: coderTG | 来源:发表于2024-02-26 15:25 被阅读0次

HashMap的七种循环遍历方法

public class mapDemo {

public static void main(String[] args) {
    // 创建并赋值HashMap
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(2, "C语言");
    map.put(3, "php");

    // 遍历map
    // 第一种方法  迭代器EntrySet
    Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()){
        Map.Entry<Integer, String> next = iterator.next();
        System.out.print(next.getKey());
        System.out.print(next.getValue());
    }
    System.out.println("---------------");
    // 第二种方法 迭代器 keySet
    Iterator<Integer> iterator1 = map.keySet().iterator();
    while (iterator1.hasNext()){
        Integer next = iterator1.next();
        System.out.print(next);
        System.out.print(map.get(next));
    }
    System.out.println("---------------");
    // 第三种 forEach EntrySet
    for (Map.Entry<Integer, String> next: map.entrySet()) {
        System.out.print(next.getKey());
        System.out.print(next.getValue());
    }
    System.out.println("---------------");
    // 第四种 forEach Keyset
    for(Integer key : map.keySet()){
        System.out.print(key);
        System.out.print(map.get(key));
    }
    System.out.println("---------------");
    // 第五种 lambda
    map.forEach((key, value) ->{
        System.out.print(key);
        System.out.print(value);
    });
    System.out.println("---------------");
    // 第六种 Streams Api 单线程
    map.entrySet().stream().forEach((entry) ->{
        System.out.print(entry.getKey());
        System.out.print(entry.getValue());
    });
    System.out.println("---------------");
    // 第七种 Streams API 多线程
    map.entrySet().parallelStream().forEach((entry) ->{
        System.out.print(entry.getKey());
        System.out.print(entry.getValue());
    });
    System.out.println("---------------");
}

}
运行结果:


image.png

相关文章

网友评论

      本文标题:HashMap的七种循环遍历

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