跳至主要內容

Map

Jin...大约 2 分钟

Map

1、Java中遍历Map的五种方式

方法一:在for循环中遍历value

    Map<String, String> map = new HashMap();
    map.put("开发", "开发");
    map.put("测试", "测试");
    for (Object value : map.values()) {
        System.out.println("第一种:" + value);
    }

方法二::通过key遍历

    for (String key: map.keySet()) {
        System.out.println("第二种:" + map.get(key));
    }

方法三::通过entrySet实现遍历

	Set<Map.Entry<String, String>> entrySet = map.entrySet();
    for (Map.Entry entry : entrySet) {
        System.out.println("第三种:" + entry.getKey() + " :" + entry.getValue());
    }

方法四::通过Iterator迭代器实现遍历

    Iterator<Map.Entry<String, String>> entryIterator = map.entrySet().iterator();
    while (entryIterator.hasNext()) {
        Map.Entry<String, String> entry = entryIterator.next();
        System.out.println("第四种:" + entry.getKey() + " :" + entry.getValue());
    }

方法五 :通过lambda表达式进行遍历

    map.forEach((key, value) -> {
        System.out.println("第五种:" + key + " :" + value);
    });

2、API

computeIfAbsent()

hashmap.computeIfAbsent(K key, Function remappingFunction)
  1. 方法有两个参数
    • 第一个参数是hashMapkey,第二个参数是一个方法,叫做重新映射函数,用于重新计算值(就是说value值是这个方法重新计算后的结果)。
  2. 返回值
    • 返回的就是value
  3. 作用
    • 使用这个方法时,如果说key不存在或者为null时,那么直接把key添加到map中,调用remappingFunction方法
    • 如果key存在,直接返回已存在key值对应的value

key值不存在

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("HashMap: " + prices);

        // 计算 Shirt 的值
        int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
        System.out.println("Price of Shirt: " + shirtPrice);

        // 输出更新后的HashMap
        System.out.println("Updated HashMap: " + prices);
    }
}

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

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 280
Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}

key值存在

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // 创建一个 HashMap
        HashMap<String, Integer> prices = new HashMap<>();

        // 往HashMap中添加映射关系
        prices.put("Shoes", 180);
        prices.put("Bag", 300);
        prices.put("Pant", 150);
        System.out.println("HashMap: " + prices);

        // Shoes中的映射关系已经存在
        // Shoes并没有计算新值
        int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
        System.out.println("Price of Shoes: " + shoePrice);

        // 输出更新后的 HashMap
        System.out.println("Updated HashMap: " + prices);
    }
}

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

HashMap: {Pant=150, Bag=300, Shoes=180}
Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}

在以上实例中, Shoes 的映射关系在 HashMap 中已经存在,所以不会为 Shoes 计算新值。

贡献者: Jin
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度