HashMap循环迭代的5种方式

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

Map 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> entries = map.entrySet().iterator();
    while (entries.hasNext()) {
      Map.Entry entry = entries.next();
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
//    4、使用键的迭代器进行遍历
    System.out.println("第4种:");
    Iterator 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 action) {
    Objects.requireNonNull(action);
    for (Map.Entry 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);
    }
}

你可能感兴趣的:(java)