Вопрос

Suppose to have an object from the class Target and a set of objects from the class FriendOfTarget, e.g.

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{
    //
}

If I want to construct a list of FriendOfTarget objects, in Java7 I do the following inside the method reduceByParam from class Target:

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

How can I do the same in Java8? I have some difficulties to find examples on how to refer to this into the anyMatch method of a stream.

Это было полезно?

Решение

There are two ways to implement a functional interface, that refers to this:

  • Lambda expression: fot -> reduceByThis(fot)
  • Method reference: this::reduceByThis

A lambda expression can access this in the same way as the enclosing scope. That means you can invoke the method reduceByThis both with and without qualification. For the method reference, that target object can be explicitly bound. The following example only shows the latter:

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

You can also use this explicitly in lambda expressions. As I have already mentioned, it refers to the this of the enclosing scope (in contrast to anonymous inner classes). For example:

public List<FriendOfTarget> reduce() {
    return completeListOfFriendOfTargets
        .stream()
        .filter(fot -> fot.reduceOtherDirection(this))
        .collect(toList());
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top