Converting java 8 lambda expression to work in java 7

前端 未结 3 712
刺人心
刺人心 2021-01-01 00:04

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(ni         


        
相关标签:
3条回答
  • 2021-01-01 00:44

    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

    0 讨论(0)
  • 2021-01-01 00:46

    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)));
    
    0 讨论(0)
  • 2021-01-01 00:51

    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.

    0 讨论(0)
提交回复
热议问题