How to use Consumer in a variable (Java 8)

2

I created a data structure of my own for a game Text Adventure, and in it each Action object has a Consumer.  The next step would be to have someone type a word, scroll through the structure, and find an Action containing the String typed in a vector, run that Consumer (default value 1).  But I can not create a code of type "Action.function (1)". to get around this, I had to use forEach, like this:

public static void exec(Consumer<Integer> c, int i) {
    ArrayList<Integer> is = new ArrayList<>();
    is.add(i);
    is.forEach(c);
}

What I think is a gambiarra. Does anyone know a better way to use my Consumer within the code, without having to create a new ArrayList (or whatever) just for that?  If necessary, here is part of my Action object code:     public class Action implements Iterable {

String id;
String[] functionNames;
Consumer<Integer> function;
Action next;

public Action(String id, Consumer<Integer> function, String... names) {
    this.id = id;
    this.function = function;
    this.functionNames = names;
    this.next = null;
}

@Override
public Iterator iterator() {
    return new ActionIterator(this);
}

Thank you in advance.

    
asked by anonymous 01.12.2014 / 00:01

1 answer

1

In Java 8, a Functional Interface is any interface that has exactly 1 abstract method (it can also have default methods, or declare abstract methods of Object , but must have 1 abstract method in addition). Consumer<T> is a functional interface whose method is < a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html#accept-T-"> void accept(T) .

This is therefore the method that will be called by ArrayList.forEach , so to get an equivalent effect to your example just use:

c.accept(i);
    
01.12.2014 / 00:44