在Java 8中使用函数类型congruent lambda表达式 [英] Usage of function type congruent lambda expressions in Java 8

查看:114
本文介绍了在Java 8中使用函数类型congruent lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难定义和使用

Stream.collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)

方法

方法签名包括BiConsumer 键入的参数。 BiConsumer FunctionalInterface定义了一种功能方法 accept(Object,对象)。据我所知,我现在可以使用任何全等到这个功能界面。

The method signature includes BiConsumer typed parameters. The BiConsumer FunctionalInterface defines one functional method accept(Object, Object). As far as I understand I can now use any lambda expression that is congruent to this functional interface.

但是Stream.collect中提到的例子 JavaDoc的是例如

But the example mentioned in the Stream.collect JavaDoc is e.g.

 List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

我不明白为什么ArrayList.add(E e) (单个参数)与 BiConsumer.accept(T t,U u)方法(两个参数)并且可以在收集方法中用作累加器函数。

I do not understand why ArrayList.add(E e) (single parameter) is congruent with the BiConsumer.accept(T t, U u) method (two parameters) and can be used as the accumulator function in the collect method.

如你所见,我显然缺乏理解并理解任何解释。

As you see I obviously have a lack of understanding and appreciate any explanation.

推荐答案

累加器BiConsumer的两个参数是(1)列表本身和(2)要添加的项目。这:

The accumulator BiConsumer's two parameters are (1) the list itself and (2) the item to add to it. This:

List<String> asList = stringStream.collect(
    ArrayList::new,
    ArrayList::add,
    ArrayList::addAll
);

相当于:

List<String> asList = stringStream.collect(
    () -> new ArrayList<>(),
    (list, item) -> list.add(item),
    (list1, list2) -> list1.addAll(list2)
);

会得到与此相同的结果:

which will give the same result as this:

List<String> asList = stringStream.collect(
    new Supplier<ArrayList<String>>() {
        @Override
        public ArrayList<String> get() {
            return new ArrayList<>();
        }
    },

    new BiConsumer<ArrayList<String>,String>() {
        @Override
        public void accept(ArrayList<String> list, String item) {
            list.add(item);
        }
    },

    new BiConsumer<ArrayList<String>,ArrayList<String>>() {
        @Override
        public void accept(ArrayList<String> list1, ArrayList<String> list2) {
            list1.addAll(list2);
        }
    }
);

这篇关于在Java 8中使用函数类型congruent lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆