Page 1 of 1
About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Wed Oct 23, 2019 1:48 pm
by dongyingname
There is no correct answer, peek() only accept a Consumer as passed argument. getTitle() returns String not void, thus cannot be a Consumer.
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Wed Oct 23, 2019 9:04 pm
by admin
1. Did you try compiling and running it?
2. Recall from your OCA preparation that signature of a method does not include the return type.
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Wed Oct 23, 2019 9:16 pm
by dongyingname
I understood now.
The compiler doesn't see the return type of the lambda expression
as long as I don't write
Code: Select all
long count = bkStrm.peek(x -> {return x.getTitle();}).count();//doesn't compile
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Thu Oct 24, 2019 4:32 am
by admin
Well, bkStrm.peek(x -> {return x.getTitle();}).count(); would still be wrong and has nothing to do with the Consumer object that you are passing to the peek method. This statement doesn't compile because the method count() cannot be invoked on the type of the object returned by peek.
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Mon Jun 22, 2020 6:04 am
by daniko
What here could also be useful information, is that if the count can be calculated directly from the stream source, the intermediate operation won't be executed at all.
For example
List<String> l = Arrays.asList("A", "B", "C", "D");
long count = l.stream().peek(System.out::println).count();
The peek(System.out::println) won't be executed and the ABCD won't be printed because the count can be calculated directly from the variable l.
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Mon Jun 22, 2020 6:59 am
by admin
Well, it is good information but what you have written is not entirely correct. As per the documentation, it is up to the implementation. It says,
"An implementation may choose to not execute the stream pipeline ....".
So, it is not a guarantee that the pipeline will not be executed.
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Wed Dec 27, 2023 9:25 am
by Badem48
Hi,
I have a question.
Code: Select all
long count;
long count2;
var books = new ArrayList<Book>(List.of(new Book("The Outsider", "Stephen King"),
new Book("Becoming", "Michelle Obama"), new Book("Uri", "India")));
Stream bkStrm = books.stream();
count = bkStrm.peek(x -> x.getTitle()).count(); //line 1
count2 = books.stream().peek(x -> x.getTitle()).count(); //line 2
System.out.println(count + " " + count2);
In this code the line //line 2 works fine but on //line 1, like in the question, does not work because it uses the raw type. Why it does not use the raw type on //line 2?
Re: About Question enthuware.ocpjp.ii.v11.2.3325 :
Posted: Wed Dec 27, 2023 8:41 pm
by admin
Sorry, I did not understand your question. What error message are you getting?