zoukankan      html  css  js  c++  java
  • Map以及Set的遍历(EntrySet方法,补充enumeration和Iterator的区别)

    public void mearge(Map map) {
            Map returnMap = new HashMap<>();
            // 转换为Entry
            Set<Map.Entry<Object, Object>> entries = map.entrySet();
            // 遍历
            for (Map.Entry<Object, Object> entry : entries) {
                Object key = entry.getKey();
                Object val = entry.getValue();
                System.out.println("key:value#"+key+":"+val);
            }
        }

    主要使用了Map.entrySet()方法;Entry可以理解为单个的键值对。

    这里也跳过了set转为iterator再进行遍历的过程。直接使用foreach的方式,简洁。

    补充一个关于Enumeration和iterator的知识点,之前看到有博文指出,尽量少用enumeration,多用iterator。

    Enumeration接口主要实现的两个方法:

    boolean hasMoreElements()
    Tests if this enumeration contains more elements.
    E nextElement()
    Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

      ·boolean hasMoreElemerts() :测试Enumeration枚举对象中是否还含有元素,如果返回true,则表示还含有至少一个的元素。
          ·Object nextElement() :如果Bnumeration枚举对象还含有元素,该方法得到对象中的下一个元素。

    Iterator接口主要方法:

    boolean hasNext()
    Returns true if the iteration has more elements.
    E next()
    Returns the next element in the iteration.
    void remove()
    Removes from the underlying collection the last element returned by this iterator (optional operation).

    以上可以看出,iterator比enumeration多了个删除的方法,其他两个方法功能都相似,所以建议多使用iterator接口。

    --------------------
    做一个精神上的素食主义者。
  • 相关阅读:
    Jmeter性能监测及安装插件(推荐)
    测试用例使用传统excel还是思维导图(Xmind、MindManager等)?
    测试用例设计
    一个资深测试员的感悟
    log4j教程 10、PatternLayout
    log4j教程 9、HTMLLayout
    log4j教程 8、日志格式化
    log4j教程 7、日志记录级别
    log4j教程 6、Logger方法
    log4j教程 5、示例程序
  • 原文地址:https://www.cnblogs.com/xfile/p/4966795.html
Copyright © 2011-2022 走看看