【问题标题】:Java8: Matching and mapping with reference to thisJava8:参照this进行匹配和映射
【发布时间】:2014-04-16 08:23:00
【问题描述】:

假设有一个来自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{
    //
}

如果我想构造一个 FriendOfTarget 对象列表,在 Java7 中,我在类 Target 的方法 reduceByParam 中执行以下操作:

public List<FriendOfTarget> reduce(){
  List<FriendOfTarget> lst= new ArrayList<>();
  for(FriendOfTarget fot: completeListOfFriendOfTargets){
    if(reduceByThis(fot))
      lst.add(fot);
  }
  return lst;
}

如何在 Java8 中做同样的事情?我很难找到有关如何将this 引用到streamanyMatch 方法的示例。

【问题讨论】:

  • 第二个列表中是否有错字,应该是 reduceByParam 而不是 matchSomething。我没有看到任何与 anyMatch 相关的代码以及 this 存在问题的地方。
  • 是的,你是对的!请,您的荣幸:编辑我的问题!

标签: java list java-8 java-stream


【解决方案1】:

函数式接口有两种实现方式,即引用this

  • Lambda 表达式:fot -&gt; reduceByThis(fot)
  • 方法参考:this::reduceByThis

lambda 表达式可以访问this,方式与封闭范围相同。这意味着您可以调用 reduceByThis 方法,无论有无限定。对于方法引用,可以显式绑定该目标对象。下面的例子只展示了后者:

public List<FriendOfTarget> reduce() {
    return completeListOfFriendOfTargets
        .stream()
        .filter(this::reduceByThis)
        .collect(toList());
}

您还可以在 lambda 表达式中显式使用 this。正如我已经提到的,它指的是封闭范围的this(与匿名内部类相反)。例如:

public List<FriendOfTarget> reduce() {
    return completeListOfFriendOfTargets
        .stream()
        .filter(fot -> fot.reduceOtherDirection(this))
        .collect(toList());
}

【讨论】:

  • 起来!你说的对。因为原来不是int param,所以是这个!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多