kay
kay

Reputation: 481

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);
}

Upvotes: 8

Views: 20103

Answers (2)

Turing85
Turing85

Reputation: 20195

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:

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

Upvotes: 14

Sweeper
Sweeper

Reputation: 273075

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

Upvotes: 10

Related Questions