Expression不起作用

Expression不起作用

本文介绍了Lambda Expression不起作用,被终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用lambda表达式编写java8程序,它不会执行,而是在lambda表达式处终止,没有异常

wrote java8 program with lambda expression, its not getting executed instead its getting terminated at the lambda expression, no exceptions

    import java.util.ArrayList;
    import java.util.List;
    import java.util.function.BiConsumer;

    public class BiConsumerTest {


    public static void main(String[] args) {
        try{


        List<String> list1 = new ArrayList<String>();

        list1.add("A");
        list1.add("B");
        list1.add("V");


    List<String> list2 = new ArrayList<String>();

        list2.add("J");
        list2.add("G");
        list2.add("P");

        BiConsumer<List<String>  , List<String>> bc = (lista, listb) ->{
                lista.stream().forEach( System.out::print);

            };


        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

}

预期会在列表中打印字符串

expected is it will print the string in list

推荐答案

这是因为您没有调用BiConsumeraccept方法.称它为:

This is because you're not calling the BiConsumer's accept method. call it as follows:

  bc.accept(list1, list2);

此外,请注意,不必只调用forEach而是直接调用列表中的forEach来调用stream:

Further, note that it's not necessary to call stream just to call forEach instead call forEach directly on the list:

 lista.forEach(System.out::print);

另一件事是您的BiConsumer不使用第二个列表,这可能是因为您尚未完成整个逻辑的实现,在这种情况下,这是可以理解的.

Another thing is that your BiConsumer doesn't use the second list, this may be because you haven't finished implementing the entire logic yet in which case it's understandable.

完整代码:

BiConsumer<List<String>, List<String>> bc = (lista, listb) -> {
    lista.forEach(System.out::print);
    // listb.forEach(System.out::print);
};
bc.accept(list1, list2);

这篇关于Lambda Expression不起作用,被终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 20:26