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
Java 8 Stream interface introduces filter() method which can be used to filter out some elements from object collection based on a particular condition. This condition should be specified as a predicate which the filter() method accepts as an argument.
The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.
With Java 8, you can convert a Map. entrySet() into a stream , follow by a filter() and collect() it.
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With