问题
Hey I'm new to coding and I've kind of gotten a hold of Java 8's Lambda functions but I'm trying to convert some of the code I wrote to Java 7 for a project in school and I can't wrap my head around how to make this piece of code identical in functionality but in java 7. Sorry if this is a dumb questions but I can't seem to figure it out. Do I write a custom method and then apply it to the my PriorityQueue.
open = new PriorityQueue<>((Object o1, Object o2) -> {
Cell c1 = (Cell)o1;
Cell c2 = (Cell)o2;
return c1.endCost<c2.endCost?-1:
c1.endCost>c2.endCost?1:0;
});
回答1:
Try to use anonymous Comparator
class here:
open = new PriorityQueue<Cell>(new Comparator<Cell>() {
@Override
public int compare(Cell o1, Cell o2) {
return c1.endCost < c2.endCost ? -1 :
c1.endCost > c2.endCost ? 1 : 0;
}
});
You can do this automatically in Intellij Idea. Place cursor on ->
and hit Alt+Enter:
回答2:
Using Eclipse (I don't know about any other IDE), you can do this automatically by using Ctrl+1 -> Convert into anonymous class creation
In your case, it's a Comparator:
new Compator<>() {
public int compare(Object o1, Object o2) {
...
}
}
来源:https://stackoverflow.com/questions/49536198/convert-java-8-lambda-function-to-java-7