zoukankan      html  css  js  c++  java
  • HashMap的使用

    1. forEach方法

    HashMap中的forEach()方法用于对HashMap中的每个映射执行指定的操作。

    forEach()方法的语法为:

    hashMap.forEach(BiConsumer<K, V> action)
    

    注:hashMap是HashMap类的一个对象。
    参数说明:

    • action- 执行的操作

    实例:

    import java.util.HashMap;
    class Main {
        public static void main(String[] args) {
            // 创建一个 HashMap
            HashMap<String, Integer> prices = new HashMap<>();
            // 往 HashMap 中插入映射项
            prices.put("Shoes", 200);
            prices.put("Bag", 300);
            prices.put("Pant", 150);
            System.out.println("Normal Price: " + prices);
            System.out.print("Discounted Price: ");
            //通过 lambda 表达式使用 forEach()
            prices.forEach((key, value) -> {
                // value 价格减少百分之 10
                value = value - value * 10/100;
                System.out.print(key + "=" + value + " ");
            });
        }
    }
    

    执行以上程序输出结果为:

    Normal Price: {Pant=150, Bag=300, Shoes=200}
    Discounted Price: Pant=135 Bag=270 Shoes=180 
    

    注意这一行:

    prices.forEach((key, value) -> {
        // value 价格减少百分之 10
        value = value - value * 10/100;
        System.out.print(key + "=" + value + " ");
    });
    

    以上实例中,我们将匿名函数 lambda 的表达式作为forEach()方法的参数传入,lambda 表达式将动态数组中的每个元素减少百分 10,然后输出结果。

  • 相关阅读:
    caffe学习笔记(1)安装
    windows下遍历文件夹
    图像处理之OpenCV
    OpenCV的安装和使用
    使用cpplint检测代码规范
    图像处理之原理
    Python 在cmd中import模块成功,但是在jupyter notebook中No module xxx found
    Win10上使用VS2015编译Caffe2
    Win10, VS2017环境下OpenCV3.4.2的配置
    C++ main函数的参数
  • 原文地址:https://www.cnblogs.com/muuu520/p/14503163.html
Copyright © 2011-2022 走看看