Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java consumers ability to accept and return boolean or string

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);
}
like image 636
kay Avatar asked Dec 14 '22 16:12

kay


2 Answers

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>.

like image 160
Sweeper Avatar answered Dec 16 '22 06:12

Sweeper


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:

  • for int: ToIntFunction<String>,
  • for long: ToLongFunction<String>, and
  • for double: 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...

like image 33
Turing85 Avatar answered Dec 16 '22 06:12

Turing85