使用lambdas的Java控制台菜单

使用lambdas的Java控制台菜单,java,lambda,Java,Lambda,我正在学习如何用Java创建一个基本的控制台菜单。有人告诉我,用lambda's做这件事会更有效率。这里的代码在没有lambda的情况下可以正常工作,但是我想知道如何修改它,以便可以使用lambda的方法将方法添加到menu类中 另外,为什么使用lambda会使其更好/更高效?或者它只是让代码更容易阅读 以下是课程: 可运行界面 @FunctionalInterface public interface Runnable { public void run(); } 选秀班 publi

我正在学习如何用Java创建一个基本的控制台菜单。有人告诉我,用lambda's做这件事会更有效率。这里的代码在没有lambda的情况下可以正常工作,但是我想知道如何修改它,以便可以使用lambda的方法将方法添加到menu类中

另外,为什么使用lambda会使其更好/更高效?或者它只是让代码更容易阅读

以下是课程:

可运行界面

@FunctionalInterface
public interface Runnable {
    public void run();
}
选秀班

public class ChoicePair<String, Runnable> {
    private String text;
    private Runnable funcint;

    public ChoicePair(String t, Runnable fi) {
        this.text = t;
        this.funcint = fi;
    }

    public void setText(String t) {this.text = t;}
    public void setFI(Runnable fi) {this.funcint = fi;}
    public String getText() {return this.text;}
    public Runnable getFI() {return this.funcint;}

}
import java.util.ArrayList;
import java.util.Scanner;

public class Menu implements Runnable {

    private String title;
    private ArrayList<ChoicePair> choices;
    public Scanner scan = new Scanner(System.in);
    public Menu(String title) {
        this.title = title;
        choices = new ArrayList<ChoicePair>();
    }

    @Override
    public void run() {
        int choiceInt = -1;
        while(choiceInt != 0) {
            System.out.println(title + ":");
            int x = 1;
            for (ChoicePair cur : choices) {
                System.out.println("[" + x + "]: " + cur.getText());
                x++;
            }
            if (title == "Main Menu")
                System.out.println("[0]: EXIT");
            else
                System.out.println("[0]: Back");
            System.out.println(">\t");
            choiceInt = getInt();
            act(choiceInt);
        }
    }
    public void addPair(ChoicePair addition) {
        choices.add(addition);
    }

    public int getInt() {
        return scan.nextInt();
    }

    public void act(int choiceInt) {
        if(choiceInt == 0)
            return;
        if(choiceInt < 0 || choiceInt > choices.size()) {
            System.out.println("Incorrect input.");
            return;
        }
        int choicePos = choiceInt - 1;
        ((Runnable)choices.get(choicePos).getFI()).run();
    }

}
import java.util.*;

public class Application {
    public static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
        Menu mainMenu = new Menu("Main Menu");

        //Create runnables for setting mean types...
        Runnable setMean1 = new Runnable() {
            @Override
            public void run() {
                meanCalculator.setType(1);
                System.out.println("Mean type set to Arithmetic.");
            }
        };
        Runnable setMean2 = new Runnable() {
            @Override
            public void run() {
                meanCalculator.setType(2);
                System.out.println("Mean type set to Geometric...");
            }
        };
        Runnable setMean3 = new Runnable() {
            @Override
            public void run() {
                meanCalculator.setType(3);
                System.out.println("Mean type set to Harmonic...");
            }
        };
        //Create mean-setting menu and choicepairs and populate.
        Menu setMean = new Menu("Set Mean Type");
        ChoicePair mean1 = new ChoicePair("Arithmetic", setMean1);
        ChoicePair mean2 = new ChoicePair("Geometric", setMean2);
        ChoicePair mean3 = new ChoicePair("Harmonic", setMean3);
        setMean.addPair(mean1);
        setMean.addPair(mean2);
        setMean.addPair(mean3);
        mainMenu.addPair(new ChoicePair("Set Mean Type", setMean));

        //Create runnables for array setting...
        Runnable addValues = new Runnable() {
            @Override
            public void run() {
                ArrayList<Double> additionArrayList = new ArrayList<Double>();
                String input = null;
                int x = 0;
                System.out.print("Enter values to add to set, or '-1' to complete entry.\n> ");
                while (input != "-1") {
                    input = scan.nextLine();
                    if (Double.parseDouble(input) == -1.0D)
                        break;
                    additionArrayList.add(Double.parseDouble(input));
                }
                System.out.println("Break detected.");
                double[] additions = new double[additionArrayList.size()];
                for(double d: additionArrayList) {
                    additions[x] = d;
                    x++;
                }
                meanCalculator.addValues(additions);
            }
        };
        Runnable clearSet = new Runnable() {
            @Override
            public void run() {
                meanCalculator.clearSet();
            }
        };
        Runnable removeN = new Runnable() {
            @Override
            public void run() {
                System.out.print("Enter number of elements to remove from end\n> ");
                int toRemove = scan.nextInt();
                meanCalculator.removeN(toRemove);
            }
        };
        Runnable displaySet = new Runnable() {
            @Override
            public void run() {
                meanCalculator.display();
            }
        };
        ChoicePair add = new ChoicePair("Add values to Array", addValues);
        ChoicePair clear = new ChoicePair("Clear Array", clearSet);
        ChoicePair remove = new ChoicePair("Remove N elements", removeN);
        ChoicePair display = new ChoicePair("Display Array", displaySet);
        Menu arrayOptions = new Menu("Array Options");
        arrayOptions.addPair(add);
        arrayOptions.addPair(clear);
        arrayOptions.addPair(remove);
        arrayOptions.addPair(display);
        mainMenu.addPair(new ChoicePair("Array Options", arrayOptions));

        //Create runnable for calculate-mean function...
        Runnable calcMean = new Runnable() {
            @Override
            public void run() {
                double mean = meanCalculator.calcMean();
                String type = meanCalculator.getType();
                System.out.println(type + " mean for current array = " + mean);
            }
        };
        ChoicePair calculate = new ChoicePair("Calculate Mean", calcMean);
        mainMenu.addPair(calculate);



        //Run the main menu
        mainMenu.run();
    }
}
public class ChoicePair{
私有字符串文本;
私有可运行functint;
公共选秀节目(t字串,可运行fi){
this.text=t;
this.funcint=fi;
}
public void setText(字符串t){this.text=t;}
public void setFI(Runnable fi){this.funcint=fi;}
公共字符串getText(){返回this.text;}
public Runnable getFI(){返回this.funcint;}
}
菜单类

public class ChoicePair<String, Runnable> {
    private String text;
    private Runnable funcint;

    public ChoicePair(String t, Runnable fi) {
        this.text = t;
        this.funcint = fi;
    }

    public void setText(String t) {this.text = t;}
    public void setFI(Runnable fi) {this.funcint = fi;}
    public String getText() {return this.text;}
    public Runnable getFI() {return this.funcint;}

}
import java.util.ArrayList;
import java.util.Scanner;

public class Menu implements Runnable {

    private String title;
    private ArrayList<ChoicePair> choices;
    public Scanner scan = new Scanner(System.in);
    public Menu(String title) {
        this.title = title;
        choices = new ArrayList<ChoicePair>();
    }

    @Override
    public void run() {
        int choiceInt = -1;
        while(choiceInt != 0) {
            System.out.println(title + ":");
            int x = 1;
            for (ChoicePair cur : choices) {
                System.out.println("[" + x + "]: " + cur.getText());
                x++;
            }
            if (title == "Main Menu")
                System.out.println("[0]: EXIT");
            else
                System.out.println("[0]: Back");
            System.out.println(">\t");
            choiceInt = getInt();
            act(choiceInt);
        }
    }
    public void addPair(ChoicePair addition) {
        choices.add(addition);
    }

    public int getInt() {
        return scan.nextInt();
    }

    public void act(int choiceInt) {
        if(choiceInt == 0)
            return;
        if(choiceInt < 0 || choiceInt > choices.size()) {
            System.out.println("Incorrect input.");
            return;
        }
        int choicePos = choiceInt - 1;
        ((Runnable)choices.get(choicePos).getFI()).run();
    }

}
import java.util.*;

public class Application {
    public static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
        Menu mainMenu = new Menu("Main Menu");

        //Create runnables for setting mean types...
        Runnable setMean1 = new Runnable() {
            @Override
            public void run() {
                meanCalculator.setType(1);
                System.out.println("Mean type set to Arithmetic.");
            }
        };
        Runnable setMean2 = new Runnable() {
            @Override
            public void run() {
                meanCalculator.setType(2);
                System.out.println("Mean type set to Geometric...");
            }
        };
        Runnable setMean3 = new Runnable() {
            @Override
            public void run() {
                meanCalculator.setType(3);
                System.out.println("Mean type set to Harmonic...");
            }
        };
        //Create mean-setting menu and choicepairs and populate.
        Menu setMean = new Menu("Set Mean Type");
        ChoicePair mean1 = new ChoicePair("Arithmetic", setMean1);
        ChoicePair mean2 = new ChoicePair("Geometric", setMean2);
        ChoicePair mean3 = new ChoicePair("Harmonic", setMean3);
        setMean.addPair(mean1);
        setMean.addPair(mean2);
        setMean.addPair(mean3);
        mainMenu.addPair(new ChoicePair("Set Mean Type", setMean));

        //Create runnables for array setting...
        Runnable addValues = new Runnable() {
            @Override
            public void run() {
                ArrayList<Double> additionArrayList = new ArrayList<Double>();
                String input = null;
                int x = 0;
                System.out.print("Enter values to add to set, or '-1' to complete entry.\n> ");
                while (input != "-1") {
                    input = scan.nextLine();
                    if (Double.parseDouble(input) == -1.0D)
                        break;
                    additionArrayList.add(Double.parseDouble(input));
                }
                System.out.println("Break detected.");
                double[] additions = new double[additionArrayList.size()];
                for(double d: additionArrayList) {
                    additions[x] = d;
                    x++;
                }
                meanCalculator.addValues(additions);
            }
        };
        Runnable clearSet = new Runnable() {
            @Override
            public void run() {
                meanCalculator.clearSet();
            }
        };
        Runnable removeN = new Runnable() {
            @Override
            public void run() {
                System.out.print("Enter number of elements to remove from end\n> ");
                int toRemove = scan.nextInt();
                meanCalculator.removeN(toRemove);
            }
        };
        Runnable displaySet = new Runnable() {
            @Override
            public void run() {
                meanCalculator.display();
            }
        };
        ChoicePair add = new ChoicePair("Add values to Array", addValues);
        ChoicePair clear = new ChoicePair("Clear Array", clearSet);
        ChoicePair remove = new ChoicePair("Remove N elements", removeN);
        ChoicePair display = new ChoicePair("Display Array", displaySet);
        Menu arrayOptions = new Menu("Array Options");
        arrayOptions.addPair(add);
        arrayOptions.addPair(clear);
        arrayOptions.addPair(remove);
        arrayOptions.addPair(display);
        mainMenu.addPair(new ChoicePair("Array Options", arrayOptions));

        //Create runnable for calculate-mean function...
        Runnable calcMean = new Runnable() {
            @Override
            public void run() {
                double mean = meanCalculator.calcMean();
                String type = meanCalculator.getType();
                System.out.println(type + " mean for current array = " + mean);
            }
        };
        ChoicePair calculate = new ChoicePair("Calculate Mean", calcMean);
        mainMenu.addPair(calculate);



        //Run the main menu
        mainMenu.run();
    }
}
import java.util.ArrayList;
导入java.util.Scanner;
公共类菜单实现可运行{
私有字符串标题;
私人ArrayList选择;
公共扫描仪扫描=新扫描仪(System.in);
公共菜单(字符串标题){
this.title=标题;
choices=newarraylist();
}
@凌驾
公开募捐{
int choiceInt=-1;
while(choiceInt!=0){
System.out.println(标题+“:”);
int x=1;
for(ChoicePair cur:选项){
System.out.println(“[”+x+“]:“+cur.getText());
x++;
}
如果(标题==“主菜单”)
System.out.println(“[0]:退出”);
其他的
System.out.println(“[0]:Back”);
System.out.println(“>\t”);
choiceInt=getInt();
行动(选择);
}
}
公共无效添加对(ChoicePair添加){
选择。添加(添加);
}
公共int getInt(){
返回scan.nextInt();
}
公共无效法案(内部选择){
如果(choiceInt==0)
返回;
if(choiceInt<0 | | choiceInt>choices.size()){
System.out.println(“输入错误”);
返回;
}
int choicePos=choiceInt-1;
((Runnable)choices.get(choicePos.getFI()).run();
}
}
平均计算器类(包含使用的方法)

公共类计算器{
私有静态双[]值;
私有静态int类型;
公共计算机(){
}
公共静态无效设置值(双[]输入){
values=input.clone();
}
公共静态void addvalue(双[]加法){
如果(值==null){
value=addition.clone();
返回;
}
double[]temp=新的double[values.length+addition.length];
int-y;
对于(y=0;y
应用程序(主类)

import java.util.*;
公共类应用程序{
公共静态扫描仪扫描=新扫描仪(System.in);
公共静态void main(字符串[]args){
菜单主菜单=新菜单(“主菜单”);
//创建用于设置平均类型的可运行项。。。
Runnable setMean1=新的Runnable(){
@凌驾
公开募捐{
设置类型(1);
System.out.println(“平均类型设置为算术”);
}
};
Runnable setMean2=新的Runnable(){
@凌驾
公开募捐{
平均值计算器.setType(2);
System.out.println(“平均类型设置为几何…”);
}
};
朗恩