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

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

以LinkedHashMap为例

forEach方法:

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

再来看BiConsumer

@FunctionalInterface
public interface BiConsumer {

    /**
     * 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 andThen(BiConsumer 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 map = new LinkedHashMap();
        map.put("1", "西游记");
        map.put("2", "三国演义");
        map.put("3", "水浒传");
        map.put("4", "红楼梦");
        //采用lambda表达式写法
        map.forEach((k, v) -> print(k, v));
        //采用普通得写法
         map.forEach(new BiConsumer() {
            @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表达式在项目中使用比较多,所以分享一下!

你可能感兴趣的:(技术点)