4

I know how to declare an array of other things, like strings, in this way:

String[] strings = { "one", "two", "tree" };
// or
String[] strings = new String[] { "one", "two", "tree" };

But when it comes to method references, I can't figure out how to avoid having to create a list and add every item individually.

Example: Call the method smartListMerge on several diferent matching lists from two sources:

List<Function<TodoUser, TodoList>> listGetters = new ArrayList<>(3);
listGetters.add(TodoUser::getPendingList);
listGetters.add(TodoUser::getCompletedList);
listGetters.add(TodoUser::getWishList);

TodoUser userA = ..., userB = ...;
for (Function<TodoAppUser, TodoList> listSupplier : listGetters) {
    TodoList sourceList = listSupplier.apply(userA);
    TodoList destinationList = listSupplier.apply(userB);

    smartListMerge(sourceList, destinationList);
}

What is the right way to declare an array of method references?

Igor Soarez
  • 6,335
  • 1
  • 14
  • 14

3 Answers3

3

There are shorter ways to create a List:

List<Function<TodoUser, TodoList>> listGetters = Arrays.asList(TodoUser::getPendingList,
                                                               TodoUser::getCompletedList,
                                                               TodoUser::getWishList);

or (in Java 9):

List<Function<TodoUser, TodoList>> listGetters = List.of(TodoUser::getPendingList,
                                                         TodoUser::getCompletedList,
                                                         TodoUser::getWishList);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • `What is the right way to declare an array of method references` - OP asks, `List#of` or `Arrays#asList` the answer :) +1, but still funny – Eugene Mar 12 '18 at 13:17
1

In your question, you asked of an array of methods. You can define it like this:

Method toString = String.class.getMethod("toString"); // This needs to catch NoSuchMethodException.
Method[] methods = new Method[] { toString };

Yet, in your example you work with functionals, which you can also put into an array:

Function<String, String> toStringFunc = String::toString;
Function[] funcs = new Function[] { toStringFunc };

Keep in mind to import java.lang.reflection.Method for the first or java.util.function.Function for the second example, respectively.

As far as I know, there is no shorthand for defining a list.

E_3
  • 181
  • 7
0

You can't create a generic array, but you can declare one (there is warning though):

@SuppressWarnings("unchecked")
Function<String, Integer>[] arr = new Function[2];
arr[0] = String::length;
Eugene
  • 117,005
  • 15
  • 201
  • 306