Convert Java 8 Lambda Function to Java 7

好久不见. 提交于 2021-01-21 10:27:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!