我习惯于像这样声明数组内联:
String s1 = "world";
String[] strings = { "world" };
为什么我不能为功能做同样的事情?鉴于我的课程Book
包含getTitle()
和getAuthor()
方法,这是有效的:
Function<Book, String> f1 = Book::getTitle;
System.out.println(f1.apply(myBook));
然而,这不是:
Function<Book, String>[] funcs = { Book::getTitle, Book::getAuthor };
for (Function<Book, String> f2 : funcs) {
System.out.println(f2.apply(myBook));
}
它不喜欢内联数组声明,编译器错误是“无法创建函数的通用数组”
修改 我认为我的问题不是建议的重复,因为我想使用数组初始化语法静态定义一组函数
答案 0 :(得分:2)
你可以试试这个:
public static void testFunction() {
Map<String, Function<Book, String>> mapToFunctions = new HashMap<>();
Function<Book, String> myFunction = x -> new String(x.getTitle());
mapToFunctions.put("firstfunction", myFunction);
for (Function<Book, String> f : mapToFunctions.values()) {
System.out.println(f.apply(new Book("my title")));
}
}
更新:
使用Set<Function<Book, String>>
就像是:
package com.victor.main;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
public class FunctionalTest {
public static void testFunction() {
Set<Function<Book, String>> mapToFunctions = new HashSet<>();
Function<Book, String> myFunction = x -> new String(x.getTitle());
mapToFunctions.add(myFunction);
for (Function<Book, String> f : mapToFunctions) {
System.out.println(f.apply(new Book("my title")));
}
}
public static void main(String[] args) {
testFunction();
}
}