Writing a function inside the main method - Java

前端 未结 7 2165
半阙折子戏
半阙折子戏 2020-12-06 11:36

Can you write a method inside the main method? For example I found this code:

public class TestMax {
    public static void main(String[] args) {
    int i =         


        
7条回答
  •  难免孤独
    2020-12-06 12:33

    Yes, this is possible by lembda expression: for that you should use at least java 8

    import java.util.function.BiFunction;
    
    public class TestMax {
        public static void main(String[] args) {
            BiFunction max = (a,b)-> a>b ? a : b;
    
            //now you can call method
    
            int i = 5;
            int j = 2;
            int k = max.apply(i, j);
            System.out.println("The maximum between is " + k);
        }
    }
    

    BiFunction is an functional interface java compiler internally converts lambda expression code as an anonymouse class which implements BiFunction interface and overrides apply() method which contains your code

    Internal (compiler considered) code is:

    BiFunction max = new BiFunction(){
        public Integer apply(Integer a, Integer b){
            return a>b ? a : b; //your code
        }
    }
    

提交回复
热议问题