浅析Map集合forEach循环与lambda表达式

java8 新特性增加了lambda表达式,所谓的lambda表达式,即(参数) -> {方法体},如果只有一个形参,括号加声明类型可以省略,方法体只有一个行也可以省略,有返回值得方法中只有一行代码,可以省略大括号和return,只写条件。只有函数式接口才可以使用lambda表达式。

以LinkedHashMap为例

forEach方法:

public void forEach(BiConsumer<? super K, ? super V> action) {
        if (action == null)
            throw new NullPointerException();
        int mc = modCount;
        for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
            action.accept(e.key, e.value);
        if (modCount != mc)
            throw new ConcurrentModificationException();
    }

再来看BiConsumer

@FunctionalInterface
public interface BiConsumer<T, U> {

    /**
     * Performs this operation on the given arguments.
     *
     * @param t the first input argument
     * @param u the second input argument
     */
    void accept(T t, U u);

    /**
     * Returns a composed {@code BiConsumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code BiConsumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
        Objects.requireNonNull(after);

        return (l, r) -> {
            accept(l, r);
            after.accept(l, r);
        };
    }
}

此接口为函数式接口,所以可以使用lambda表达式

例:

public class TestLinkedHashMap {

    public static void main(String[] args) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("1", "西游记");
        map.put("2", "三国演义");
        map.put("3", "水浒传");
        map.put("4", "红楼梦");
        //采用lambda表达式写法
        map.forEach((k, v) -> print(k, v));
        //采用普通得写法
         map.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(String s, String s2) {
                print(s, s2);
            }
        });
    }

    public static void print(String k, String v) {
        System.out.println("k:" + k + ",v:" + v);
    }

}

由于BiConsumer接口实现方法中只调用一个print()方法,所以()-> {}  大括号可以省略。

forEach配合lambda表达式在项目中使用比较多,所以分享一下!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值