Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expression is not working, getting terminated

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

like image 561
user1245524 Avatar asked Jan 02 '19 11:01

user1245524


2 Answers

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);
like image 88
Ousmane D. Avatar answered Oct 06 '22 09:10

Ousmane D.


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);
like image 24
Naman Avatar answered Oct 06 '22 09:10

Naman