I am learning Java 8 lambda and streams and trying some examples. But facing problem with it. here is my code
fillUpdate(Person p){ List<Address> notes = getAddress(); notes.stream().filter( addr -> addr !=null).map( this::preparePersonInfo,p,addr); } private void preparePersonInfo(Person p, Address addr){ // do some stuff }
Am getting compilation error in .map addr(second argument) field. what wrong in it and could you please provide links to learn java 8 streams. FYI am following this link Java 8 lambda
Advertisement
Answer
The first problem is that map
method call doesn’t declare the addr
variable.
The second problem is the usage of a method with no return type in map
.
You can’t use a method reference the way to tried (map( this::preparePersonInfo,p,addr)
), since the parameters for a method reference are passed implicitly. If preparePersonInfo
only required a single Address
argument, you could write:
notes.stream().filter( addr -> addr !=null).forEach(this::preparePersonInfo);
since in this case the Address
argument would be passed from the Stream.
You probably want to add some terminal operation to the Stream pipeline, or it won’t be processed. Since your preparePersonInfo
doesn’t return anything, it can’t be used in map
(as map
maps the Stream element to something else, so it must return something). Perhaps forEach
would suit your needs if all you want is to execute an operation on each element of the Stream that passes the filter.
Therefore, the following should work with your current preparePersonInfo
method:
notes.stream().filter( addr -> addr !=null).forEach (addr -> preparePersonInfo(p,addr));