Java 8 functional interface with no arguments and no return value

后端 未结 3 685
心在旅途
心在旅途 2020-12-08 18:00

What is the Java 8 functional interface for a method that takes nothing and returns nothing?

I.e., the equivalent to to the C# parameterless Action wit

3条回答
  •  旧巷少年郎
    2020-12-08 18:32

    Just make your own

    @FunctionalInterface
    public interface Procedure {
        void run();
    
        default Procedure andThen(Procedure after){
            return () -> {
                this.run();
                after.run();
            };
        }
    
        default Procedure compose(Procedure before){
            return () -> {
                before.run();
                this.run();
            };
        }
    }
    

    and use it like this

    public static void main(String[] args){
        Procedure procedure1 = () -> System.out.print("Hello");
        Procedure procedure2 = () -> System.out.print("World");
    
        procedure1.andThen(procedure2).run();
        System.out.println();
        procedure1.compose(procedure2).run();
    
    }
    

    and the output

    HelloWorld
    WorldHello
    

提交回复
热议问题