当前位置:   article > 正文

HashMap循环迭代的5种方式_hashmap 迭代

hashmap 迭代
面试的时候被问了hashmap迭代方式有几种,现记录以下5种方式,方便日后使用:    

Map<String,MediaEquipment> map=new HashMap<>(2);
    MediaEquipment mediaEquipment=new MediaEquipment();
    mediaEquipment.setEquipmentId(1001L);
    mediaEquipment.setEquipmentNum("设备1");
    MediaEquipment mediaEquipment1=new MediaEquipment();
    mediaEquipment1.setEquipmentId(1002L);
    mediaEquipment1.setEquipmentNum("设备2");
    map.put(mediaEquipment.getEquipmentId().toString(),mediaEquipment);
    map.put(mediaEquipment1.getEquipmentId().toString(),mediaEquipment1);

//    1、 通过ForEach循环进行遍历(常用)
    System.out.println("第1种:");
    for (Map.Entry entry:map.entrySet()) {
      System.out.println("key"+entry.getKey()+"--values"+entry.getValue());
    }
//    2、 ForEach迭代键值对方式
    System.out.println("第2种:");
    for (String key:map.keySet()) {
      System.out.print(key+",");
    }
    System.out.println();
    for (MediaEquipment me:map.values()) {
      System.out.println(JSON.toJSONString(me));
    }
//    3、使用带泛型的迭代器进行遍历
    System.out.println("第3种:");
    Iterator<Entry<String, MediaEquipment>> entries = map.entrySet().iterator();
    while (entries.hasNext()) {
      Map.Entry<String, MediaEquipment> entry = entries.next();
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
//    4、使用键的迭代器进行遍历
    System.out.println("第4种:");
    Iterator<String> entsets = map.keySet().iterator();
    while (entsets.hasNext()) {
      System.out.println("Key = " + map.get(entsets.next()) + ", Value = " + JSON.toJSONString(map.get(entsets.next())));
    }
//    5、通过Java8 Lambda表达式遍历
    map.forEach((k, v) -> System.out.println("第5种:key: " + k + " value:" + v));

其中第5种还是采用第第一种模式进行迭代封装,源码如下:

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/460869
推荐阅读
相关标签
  

闽ICP备14008679号