Lambda Expression is not working, getting terminated

雨燕双飞 提交于 2019-12-05 09:17:54

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

  bc.accept(list1, list2);

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);

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.

Complete code:

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

You've currently just defined the functional interface, to execute it further you need to invoke the implementation in your code. In your case, for this, you need to call the BiConsumer.accept method as:

bc.accept(list1, list2);

which then performs the operation, you've defined. As its Javadoc states

Performs this operation on the given arguments.


On another note, if I was to suggest, you might just be intending to print(at least) both the lists that you are consuming as :

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

which would print as an output A B V J G P.

(From comments) This could further be written as :

BiConsumer<List<String>, List<String>> biConsumer =
                      (lista, listb) -> Stream.concat(lista.stream(), listb.stream())
                                              .forEach( System.out::print);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!