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

  • 相关阅读:
    Docker 私有仓库搭建
    事务提交与不同数据库的自增方式
    多环境切换&&注解方式&&增删改返回值问题
    查询缓存&&逆向工程
    Mybatis整合Log4j、延迟加载
    关联查询
    MyBatis实现动态SQL
    输出参数resultType
    MyBatis调用存储过程执行CRUD
    两种取值符号的异同
  • 原文地址:https://www.cnblogs.com/muuu520/p/14503163.html
Copyright © 2011-2022 走看看