Converting java 8 lambda expression to work in jav

2019-02-10 21:19发布

Trying to convert the this section of code to get rid of the lambda expressions so it'll be able to work in java 7

System.out.println(nicksGraph.findPath(nicksGraph.nodeWith(new Coordinate(0,0)), (a->a.getX()==3 && a.getY()==1), new PriorityQueue<Node<Coordinate>, Integer>(funcTotal)));

I've looked around but maybe I'm just not understanding it correctly.

标签: java lambda
3条回答
欢心
2楼-- · 2019-02-10 22:00

In Java 8, a lambda expression is a substitute for an anonymous inner class that implements a functional interface. It looks like here you're using a Predicate, because the expression is a boolean.

The Predicate interface was introduced in Java 8, so you need to re-create it yourself. You will not be able to create default or static methods, so just keep the functional interface method.

public interface Predicate<T>
{
    public boolean test(T t);
}

Then, replace the lambda expression with the anonymous class declaration.

System.out.println(nicksGraph.findPath(
    nicksGraph.nodeWith(new Coordinate(0,0)),
    // Replacement anonymous inner class here.
    new Predicate<Coordinate>() {
       @Override
       public boolean test(Coordinate a) {
          // return the lambda expression here.
          return a.getX()==3 && a.getY()==1;
       }
    },
    new PriorityQueue<Node<Coordinate>, Integer>(funcTotal)));
查看更多
Luminary・发光体
3楼-- · 2019-02-10 22:15

Take a look at Retrolambda. It is a backport of Java 8's lambda expressions to Java 7, 6 and 5.

Just as there was Retroweaver et al. for running Java 5 code with generics on Java 1.4, Retrolambda lets you run Java 8 code with lambda expressions, method references and try-with-resources statements on Java 7, 6 or 5. It does this by transforming your Java 8 compiled bytecode so that it can run on an older Java runtime

查看更多
欢心
4楼-- · 2019-02-10 22:20

findPath requires a Predicate as second argument. You could replace the lambda with

 new Predicate<>(){
     public boolean test(Integer i){
          return a.getX() == 3 && a.getY() == 1;
     }
 }

But the main problem will simply be the availability of Predicate itself, since it's a java8 feature. this code won't run in java7, no matter if you use lambdas or not.

查看更多
登录 后发表回答