This is a regular Consumer with usage:
public static void main(String[] args){
Consumer<String> consumer = (str) -> {
//stuff
};
consumer.accept(args[0]);
}
Here is what I am attempting to do (make it so consumer returns as boolean)
public static void main(String[] args){
Consumer<String> consumer = (str) -> {
return str.equals("yes"); //type mis-match error because consumer is void not boolean
};
boolean a = consumer.accept(args[0]); //type mis-match error because consumer is void not boolean
}
How can I manipulate consumer to return as a boolean?
Without obviously creating a whole new interface.... (below)
public interface ConsumerB {
boolean accept(String s);
}
A consumer that returns something is not a consumer anymore. It becomes a Predicate<String>:
Predicate<String> consumer = (str) -> {
return str.equals("yes");
};
You also mentioned in the title that you want the functional interface to return a String. In that case, use Function<String, String>.
For the case in which one wants to pass a String and get a boolean, one can use Predicate<String>. There are similiar functions if one wants to return one of the following primitives:
int: ToIntFunction<String>,long: ToLongFunction<String>, anddouble: ToDoubleFunction<String>.In line with the rest of the java.util.function- and the java.util.stream package, there are no further To<Primitive>Function interfaces for the primitives byte, short, char and float.
For the case in which one wants to pass a String and get a String, one can use UnaryOperator<String>.
For the general case in which one wants to pass some T and get some R, one can use Function<T, R>.
Whether this, however, improves the readability of the code is another question...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With