Java8:匹配和映射
假设有一个来自类Java8:匹配和映射,java,list,java-8,java-stream,Java,List,Java 8,Java Stream,假设有一个来自类Target的对象和一组来自类FriendOfTarget的对象,例如 public class Target{ private List<FriendOfTarget> completeListOfFriendOfTargets; public boolean matchSomething(FriendOfTarget fot){ //do something by comparing the fields of Target a
Target
的对象和一组来自类FriendOfTarget
的对象,例如
public class Target{
private List<FriendOfTarget> completeListOfFriendOfTargets;
public boolean matchSomething(FriendOfTarget fot){
//do something by comparing the fields of Target and FriendOfTarget
}
public List<FriendOfTarget> reduce(){
//
}
}
public class FriendOfTarget{
//
}
如何在Java8中实现同样的功能?我很难找到如何将
this
引用到流的anyMatch
方法中的示例有两种实现功能接口的方法,即:
- Lambda表达式:
fot->reduceByThis(fot)
- 方法参考:
this::reduceByThis
lambda表达式可以通过与封闭范围相同的方式访问此
。这意味着您可以调用方法reduceByThis
,包括有条件调用和无条件调用。对于方法引用,可以显式绑定该目标对象。以下示例仅显示了后者:
public List<FriendOfTarget> reduce() {
return completeListOfFriendOfTargets
.stream()
.filter(this::reduceByThis)
.collect(toList());
}
第二个列表中是否有输入错误,应该是reduceByParam而不是matchSomething。我没有看到任何与任何匹配相关的代码,也没有发现与此相关的问题。是的,你是对的!请,您的荣幸:编辑我的问题!不间断电源!你是对的。因为它最初不是int参数,所以是这样!
public List<FriendOfTarget> reduce() {
return completeListOfFriendOfTargets
.stream()
.filter(this::reduceByThis)
.collect(toList());
}
public List<FriendOfTarget> reduce() {
return completeListOfFriendOfTargets
.stream()
.filter(fot -> fot.reduceOtherDirection(this))
.collect(toList());
}