如何声明方法引用数组? [英] How to declare an array of method references?

查看:71
本文介绍了如何声明方法引用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何以这种方式声明其他东西的数组,比如字符串:

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.

示例:在几个不同的$ b上调用方法 smartListMerge 来自两个来源的$ b匹配列表:

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?

推荐答案

创建列表的方法较短:

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

或(在Java 9中):

or (in Java 9):

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

这篇关于如何声明方法引用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆