简体   繁体   English

带有方法调用的Java 8过滤器

[英]Java 8 filter with method call

I am learning Java 8 lambda and streams and trying some examples. 我正在学习Java 8 lambda和stream并尝试一些例子。 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. 我在.map addr (第二个参数)字段中遇到编译错误。 what wrong in it and could you please provide links to learn java 8 streams. 它有什么问题,请你提供学习java 8流的链接。 FYI am following this link Java 8 lambda 仅供参考此链接Java 8 lambda

The first problem is that map method call doesn't declare the addr variable. 第一个问题是map方法调用没有声明addr变量。

The second problem is the usage of a method with no return type in map . 第二个问题是在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. 您不能以尝试的方式使用方法引用( map( this::preparePersonInfo,p,addr) ),因为方法引用的参数是隐式传递的。 If preparePersonInfo only required a single Address argument, you could write: 如果preparePersonInfo只需要一个Address参数,你可以写:

notes.stream().filter( addr -> addr !=null).forEach(this::preparePersonInfo);

since in this case the Address argument would be passed from the Stream. 因为在这种情况下, Address参数将从Stream传递。

You probably want to add some terminal operation to the Stream pipeline, or it won't be processed. 您可能希望向Stream管道添加一些终端操作,否则它将不会被处理。 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). 由于preparePersonInfo不返回任何内容,因此无法在map (因为map将Stream元素映射到其他内容,因此它必须返回一些内容)。 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. 也许forEach会满足您的需求,如果你想要的是到通过过滤器流的每个元素上执行的操作。

Therefore, the following should work with your current preparePersonInfo method: 因此,以下内容应与您当前的preparePersonInfo方法一起使用:

notes.stream().filter( addr -> addr !=null).forEach (addr -> preparePersonInfo(p,addr));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM