Page 1 of 1
About Question enthuware.ocpjp.v8.2.1870 :
Posted: Thu May 04, 2017 6:45 am
by Kurospidey
Code: Select all
List<Integer> names = Arrays.asList(1, 2, 3); //1
names.forEach(x->x=x+1); //2
names.forEach(System.out::println); //3
Can't get my head around //2. Isn't the assignment operator supposed to return the value assigned? In this case, forEach is expecting a Consumer but is receiving a UnaryOperator.
Shouldn't it be
it will not compile due to code at //2?
Re: About Question enthuware.ocpjp.v8.2.1870 :
Posted: Thu May 04, 2017 10:16 am
by admin
Try converting the lambda expression into a method. It will be:
void or return Type m(Type x){ //deliberately left out the return type because it will be determined by where you want to use it.
(return or no return) x = x+1;
}
Now, see if it fits the case for the functional interface required by forEach i.e. Consumer's accept method, which has the signature: void accept(T t).
Yes, void accept(T t) matches nicely with void m(Type x). There is no need for the return statement. Thus, even though x = x+1 has a return value, that value will not be returned back because the lambda expression will be translated to a method with a body that doesn't have any return value statement.
HTH,
Paul.
Re: About Question enthuware.ocpjp.v8.2.1870 :
Posted: Thu May 04, 2017 11:02 am
by Kurospidey
Thanks! That one was tricky.
Re: About Question enthuware.ocpjp.v8.2.1870 :
Posted: Sat Apr 21, 2018 10:09 am
by jabenitez
Hi,
I have the following questions:
- When the values of streams are changed?
- When the values of Collections.forEach are changed?
I've seen questions where they aren't changed.
Thanks in advance.
Re: About Question enthuware.ocpjp.v8.2.1870 :
Posted: Sat Apr 21, 2018 8:41 pm
by admin
I am not sure I understand your questions. Can you post code to explain what you mean?
Re: About Question enthuware.ocpjp.v8.2.1870 :
Posted: Fri Jul 20, 2018 3:18 am
by d0wnvk@gmail.com
admin wrote: ↑Sat Apr 21, 2018 8:41 pm
I am not sure I understand your questions. Can you post code to explain what you mean?
I think the question was:
what the exact conditions
- caused the underlaying collection's elements get changed ?
- caused the stream collection's element get chanded ?
we know, that we have likely two collections in a stream situation: the first which is original (underlaying) collection, and the second which is likely 'virtual' collection, built upon underlaying colletion.
Stream can transform data, but cannot mutate data - cannot understand this statement...