How to use Consumer in a variable (Java 8)

Asked

Viewed 173 times

2

I created my own data structure for a Text Adventure game, and in it each Action object has a Consumer. The next step would be whenever someone typed a word, went through the structure and found an Action that contains the String typed in a vector, run this Consumer (default value 1). But I can’t create code like "Action.Function(1)". to get around it, 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);
}

Which sounds like a scam to me. Does anyone know a more correct 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 the code of my Action object: public class Action Iterable Mplements {

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.

  • Seria c.accept(i)?

  • It worked. Thanks! I’m new to Java 8, I’m still learning to use these new methods.

1 answer

1


In Java 8, a Functional Interface is any interface which has exactly 1 abstract method (it can also have standard methods, or declare abstract methods of Object, but needs to have 1 abstract method beyond that). Consumer<T> is a functional interface whose method is void accept(T).

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

c.accept(i);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.