请求将Java 8 Lambda实现的PriorityQueue转换为Java 7代码
Converting Java 8 Lambda PriorityQueue Initialization to Java 7
Got it, let's get this sorted for Java 7! Since Java 7 doesn't support lambda expressions, we just need to replace that lambda with an anonymous inner class that implements the Comparator<Object> interface. Here's the equivalent code for your PriorityQueue initialization:
open = new PriorityQueue<Object>(new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { Cell c1 = (Cell) o1; Cell c2 = (Cell) o2; // Paste your original lambda comparison logic here // Example: If you were comparing integer priorities, it might look like: // return Integer.compare(c1.getPriority(), c2.getPriority()); // Or whatever custom ordering logic you had in your original lambda } });
Quick Tips:
- Java 7 requires explicit implementation of the
Comparatorinterface instead of using lambdas. This anonymous inner class does exactly what your lambda was doing—defining how twoCellobjects (cast from theObjectparameters) should be ordered in the PriorityQueue. - If your original lambda used variables from the surrounding scope, remember that in Java 7 those variables must be marked
final(Java 7 doesn't support the "effectively final" behavior introduced in Java 8). So double-check any captured variables and add thefinalmodifier if needed.
内容的提问来源于stack exchange,提问作者Vladislav Varadinov
相关产品推荐
相关产品推荐

