gpt4 book ai didi

java - 如何声明一个方法引用数组?

转载 作者:搜寻专家 更新时间:2023-11-01 02:36:30 25 4
gpt4 key购买 nike

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

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

但是当涉及到方法引用时,我想不出如何避免创建一个列表并单独添加每个项目。

示例:在多个不同的节点上调用方法smartListMerge来自两个来源的匹配列表:

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

声明方法引用数组的正确方法是什么?

最佳答案

创建列表有更短的方法:

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

或(在 Java 9 中):

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

关于java - 如何声明一个方法引用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49234884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com