functional interface that takes nothing and returns nothing [duplicate]
Is there a standard functional interface in the JDK that takes nothing and returns nothing? I cannot find one. Something like the following:
@FunctionalInterface interface Action
Already answered and accepted, but this is a duplicate of stackoverflow.com/q/23868733/1441122 . That other question is kind of hard to find, though.
Indeed — I edited that other question to make it more generic (i.e., basing the question on a a C# method).
I disagree with the use Runnable advice. It miscommunicates intent: stackoverflow.com/a/76741622/501113
1 Answer 1
@FunctionalInterface public interface Runnable < /** * When an object implementing interface Runnable
is used * to create a thread, starting the thread causes the object's * run
method to be called in that separately executing * thread. * * The general contract of the method run
is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); >
FWIW. while it satisfies the functional requirement, it does not sound very semantic, Runnable is commonly associated with creating threads. A simple Worker funcional interface with a doWork method would have been nice. EDIT: Oops: stackoverflow.com/questions/27973294/…
I used Runnable in this way, and then someone saw this Runnable, and thought «runnable, aha, threads» and edited the code and forked a thread. That resulted in a bug. So nowadays I don’t use Runnable as a callback. Related question (well, answer): stackoverflow.com/a/30183786/694469
Quoting the javadoc: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. I wouldn’t recommend using Runnable just for the purpose of no parameter, void-returning functional interface.
Java 8 functional interface with no arguments and no return value
What is the Java 8 functional interface for a method that takes nothing and returns nothing? I.e., the equivalent to the C# parameterless Action with void return type?
I disagree with the use Runnable advice. It miscommunicates intent: stackoverflow.com/a/76741622/501113
4 Answers 4
If I understand correctly you want a functional interface with a method void m() . In which case you can simply use a Runnable .
Runnable ‘s interface specification indicates it is to provide executable code to the Thread class. It doesn’t seem right to me to use Runnable where it’s not intended for execution by a thread; seems misleading. Runnable is defined as a FunctionalInterface because it meets the specification of a functional interface and can be created using lambda syntax. Why not create your own functional interface? see Runnable, see FunctionalInterface
@TheSecretSquad (i) Runnable is annotated with @FunctionalInterface and (ii) even in the context of a lambda expression it will be executed on a thread: the thread in which the lambda is run which may be the current thread.
I agree with @TheSecretSquad, while it satisfies the functional requirement, it does not sound very semantic, Runnable is commonly associated with creating threads. A simple Worker functional interface with a doWork method would have been nice. EDIT: Oops: stackoverflow.com/questions/27973294/…
Fleshing out @jpangamarca’s «Oops» above: In the comments on the duplicate question he linked, Brian Goetz confirmed that Runnable was intended to be used for this purpose, not just for threading contexts.
Given that that’s the case, though, I think the javadoc should be made more generic: docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html
@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(); >; > >
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(); >
@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(); > >
i am log method. lets do it. i m1 method.
I don’t like the decision made by the Java library team to leave out the case of a no-parameter-no-return-value Function interface, and nudging those who need one to use Runnable . I think it inaccurately, and even incorrectly, redirects attention and subsequent assumptions when trying to read through a code base. Especially years after the original code was written.
Given communication and readability are far higher concerns for me and my audiences, I have composed a small helper interface designed and named in the spirit of the Java library’s missing case:
@FunctionalInterface public interface VoidSupplier
And in my case, the likelihood of an Exception being thrown in the method is considerably higher, so I actually added a checked exception like this:
@FunctionalInterface public interface VoidSupplier
Руководство Java Consumer
Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook
1- Consumer
В Java 8, Consumer — это functional interface, представляющий оператор, который принимает входной параметр и ничего не возвращает.
@FunctionalInterface public interface Consumer < void accept(T t); default ConsumerandThen(Consumer after) < Objects.requireNonNull(after); return (T t) ->< accept(t); after.accept(t); >; > >
package org.o7planning.ex; import java.util.function.Consumer; public class ConsumerEx1 < public static void main(String[] args) < // Create a Consumer object directly Consumergreeter = name -> System.out.println("Hello " + name); greeter.accept("Tran"); // Hello Tran > >
Расширяя приведенный выше пример, мы используем Consumer в методе Stream.forEach.
// A method of Stream class public void forEach(Consumer action);
package org.o7planning.ex; import java.util.function.Consumer; import java.util.stream.Stream; public class ConsumerEx2 < public static void main(String[] args) < // Create a Consumer object directly Consumergreeter = name -> System.out.println("Hello " + name); Stream names = Stream.of("Tran", "Nguyen", "Pham"); names.forEach(greeter); > >
Hello Tran Hello Nguyen Hello Pham
Modifier and Type | Method and Description |
---|---|
void | ArrayList.forEach(Consumer action) |
void | Vector.forEach(Consumer action) |
default void | PrimitiveIterator.OfDouble.forEachRemaining(Consumer action) |
default void | Spliterator.OfDouble.forEachRemaining(Consumer action) |
default void | Iterator.forEachRemaining(Consumer action) |
default void | PrimitiveIterator.OfInt.forEachRemaining(Consumer action) |
default void | Spliterator.OfInt.forEachRemaining(Consumer action) |
default void | PrimitiveIterator.OfLong.forEachRemaining(Consumer action) |
default void | Spliterator.OfLong.forEachRemaining(Consumer action) |
default void | Spliterator.forEachRemaining(Consumer action) |
void | Optional.ifPresent(Consumer consumer) |
default boolean | Spliterator.OfDouble.tryAdvance(Consumer action) |
default boolean | Spliterator.OfInt.tryAdvance(Consumer action) |
default boolean | Spliterator.OfLong.tryAdvance(Consumer action) |
boolean | Spliterator.tryAdvance(Consumer action) |
См. также: BiConsumer — это functional interface, похожий на Consumer. Разница в том, что он принимает 2 параметра:
2- Consumer + Method reference
Если метод имеет один параметр и ничего не возвращает, его ссылку можно считать Consumer.
Например: метод System.out.println(param) принимает один параметр и ничего не возвращает, тогда его ссылка System.out::println будет рассматриваться как Consumer.
package org.o7planning.ex; import java.util.function.Consumer; public class ConsumerEx5 < public static void main(String[] args) < myPrintln(System.out::println, "Hello World!"); >public static void myPrintln(Consumer c, T t) < c.accept(t); >>
package org.o7planning.ex; import java.util.stream.Stream; public class ConsumerEx6 < public static void main(String[] args) < Streamnames = Stream.of("Tran", "Nguyen", "Pham"); // Call method: Stream.forEach(Consumer) names.forEach(System.out::println); > >
3- Consumer.andThen
Метод andThen(after) возвращает ассоциированный Consumer . Сначала будет вызван текущий Consumer, а затем будет вызван after. Если на одном из двух вышеперечисленных шагов возникает ошибка, она передается вызывающему абоненту (caller). Если ошибка возникает у текущего Consumer, то after игнорируется.
default Consumer andThen(Consumer after) < Objects.requireNonNull(after); return (T t) ->< accept(t); after.accept(t); >; >
package org.o7planning.ex; import java.util.function.Consumer; public class ConsumerEx3 < public static void main(String[] args) < Consumerc = text -> System.out.println(text.toLowerCase()); c.andThen(c).accept("Hello"); > >
package org.o7planning.ex; import java.util.function.Consumer; public class ConsumerEx4 < public static void main(String[] args) < Consumerc1 = test -> test.auth(); Consumer c2 = test -> test.welcome(); UserAccount user = new UserAccount("tran", "123"); try < c1.andThen(c2).accept(user); >catch (Exception e) < >> public static class UserAccount < private String userName; private String password; public UserAccount(String userName, String password) < this.userName = userName; this.password = password; >public void auth() < if ("123".equals(password)) < System.out.println("Valid Account!"); >else < throw new RuntimeException("Invalid Password"); >> public void welcome() < System.out.println("Welcome! " + this.userName); >> >
Valid Account! Welcome! tran
View more Tutorials:
Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.
- Make iPhone Apps Using Swift, Xcode and iOS8 — 7 Apps
- Beginners Guide to Developing SQL Queries for SQL Server
- MySQL Database Development for Beginners — Lite
- Java Object-Oriented Programming : Build a Quiz Application
- Selenium WebDriver + Java для начинающих
- The Beginners Guide to SQL and PostgreSQL
- Concepts of Object Oriented Programming with C++
- * * Java Database Connection: JDBC and MySQL
- 2D Game Development With HTML5 Canvas, JS — Tic Tac Toe Game
- Creating Reports with SQL Server 2012 Reporting Services
- Core Java. Exceptions
- Scala for Java Developers (in Russian)
- * * Learn Bootstrap 4 by Example
- Create Android and iOS App using HTML, CSS and JS
- Learn Spring Boot in 100 Steps — Beginner to Expert
- The Complete Flutter UI Masterclass | iOS & Android in Dart
- Python 3000: Tactical File I/O
- Java JDBC with Oracle: Build a CRUD Application
- Build an HTML5 and CSS3 Website in 35 Minutes
- Программирование на Java с нуля
- Разработчик C# — онлайн курс программирования
- Understanding JDBC with PostgreSQL (A step by step guide)
- Complete Step By Step Java For Testers
- Learn Hibernate 4 : Java’s Popular ORM Framework