Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting java 8 lambda expression to work in java 7

Tags:

java

lambda

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.

like image 418
shmink Avatar asked Mar 17 '15 20:03

shmink


2 Answers

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)));
like image 129
rgettman Avatar answered Sep 17 '22 20:09

rgettman


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.

like image 22
Paul Avatar answered Sep 16 '22 20:09

Paul