Java 8 functional interface with no arguments and no return value

JavaJava 8Java Stream

Java Problem Overview


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 with void return type?

Java Solutions


Solution 1 - Java

If I understand correctly you want a functional interface with a method void m(). In which case you can simply use a Runnable.

Solution 2 - Java

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

Solution 3 - Java

@FunctionalInterface allows only method abstract method Hence you can instantiate that interface with lambda expression as below and you can access the interface members

        @FunctionalInterface
        interface Hai {
        
        	void m2();
        
        	static void m1() {
        		System.out.println("i m1 method:::");
        	}
        
        	default void log(String str) {
        		System.out.println("i am log method:::" + str);
        	}
        
        }
    
    public class Hello {
    	public static void main(String[] args) {
    
    		Hai hai = () -> {};
    		hai.log("lets do it.");
    		Hai.m1();
    
    	}
    }

output:

i am log method:::lets do it.
i m1 method:::

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiguel GamboaView Question on Stackoverflow
Solution 1 - JavaassyliasView Answer on Stackoverflow
Solution 2 - JavaCharanaView Answer on Stackoverflow
Solution 3 - Javauma maheshView Answer on Stackoverflow