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,然后输出结果。

  • 相关阅读:
    MySQL
    Python练习-基于socket的FTPServer
    python练习-Socket实现远程cmd命令
    python概念-Socket到底有多骚
    Python练习-天已经亮了计算器也终于完成了
    python模块-logging的智商上限
    python正则表达式-re模块的爱恨情仇
    Python练习-os模块练习-还算是那么回事儿
    Python练习-time模块
    Python练习-跨目录调用模块
  • 原文地址:https://www.cnblogs.com/muuu520/p/14503163.html
Copyright © 2011-2022 走看看