Java HashMap forEach()方法

java.util.HashMap.forEach() 对Map中的每个条目执行给定的操作,直到所有条目都已处理或该操作引发异常为止。

1 语法

public void forEach(BiConsumer<? super K,? super V> action)

2 参数

action :要对HashMap元素执行的操作。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.HashMap.forEach()方法的例子
 */
import java.util.*;
import java.util.function.BiConsumer;

public class Demo {

    // Main method
    public static void main(String[] args)
    {

        // create a HashMap and add some values
        Map<String, Integer> map
                = new HashMap<>();

        map.put("yiidian", 55);
        map.put("for", 13);
        map.put("yiidian", 22);
        map.put("is", 11);
        map.put("heaven", 90);
        map.put("for", 100);
        map.put("yiidian like us", 96);

        // creating a custom action
        BiConsumer<String, Integer> action
                = new MyBiConsumer();

        // calling forEach method
        map.forEach(action);
    }
}

// Defining Our Action in MyBiConsumer class
class MyBiConsumer implements BiConsumer<String, Integer> {

    public void accept(String k, Integer v)
    {
        System.out.print("Key = " + k);
        System.out.print("\t Value = " + v);
        System.out.println();
    }
}

输出结果为:

Key = for	 Value = 100
Key = is	 Value = 11
Key = yiidian	 Value = 22
Key = heaven	 Value = 90
Key = yiidian like us	 Value = 96

热门文章

优秀文章