mallikarjun
mallikarjun

Reputation: 1862

Java 8 filter with method call

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

Upvotes: 7

Views: 15497

Answers (2)

Smart Coder
Smart Coder

Reputation: 1738

Not exactly as asked but filter with method call --with argument-- in Lambda :

Stream<MyObject> MyObjectStream = MyObjectList.stream().filter(myobj -> StringUtils.isNotEmpty(myobj.getAccountNumber().trim()));
        MyObjectStream.forEach( o ->
                myService.getAccounts(o.getAccountNumber(), "Test"));

Upvotes: -1

Eran
Eran

Reputation: 393771

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));

Upvotes: 6

Related Questions