[英]Java passing a (lambda) function with two arguments
我正在尝试实现一个函数来读取文件,但我无法更改该方法的签名。 代码中有很多交叉引用,但也许有人可以启发我,我现在已经卡住了 3 天。
我试图传递给函数的第一种方法如下:
Purchase newPurchase = null;
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
newPurchase = new Purchase(
products.get(foundBarcode),
Integer.parseInt(purchases[1].trim())
);
不知何故,我想将此函数传递到我的导入文件函数中。
public static <E> void importItemsFromFile(List<E> items, String filePath, Function<String,E> converter) {
int originalNumItems = items.size();
Scanner scanner = createFileScanner(filePath);
// TODO read all source lines from the scanner,
// convert each line to an item of type E and
// and add each item to the list
while (scanner.hasNext()) {
// input another line with author information
String line = scanner.nextLine();
// TODO convert the line to an instance of E
E newItem = converter.apply(line);
// TODO add the item to the list of items
items.add(newItem);
}
System.out.printf("Imported %d items from %s.\n", items.size() - originalNumItems, filePath);
}
我希望有人可以帮助我并解释如何将此函数传递给另一个函数的转换器参数。 试图对这个主题进行大量研究,但我仍然无法找到答案。 请帮助我stackoverflow社区!:D
您需要先在“超级私有函数”中像这样声明
private Function<String, Purchase> doSomething() {
return textLine -> {
Purchase newPurchase = null;
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
return new Purchase(products.get(foundBarcode), Integer.parseInt(purchases[1].trim())
};
}
然后在调用这个 importItemsFromFile() 方法之前,将这个函数声明为一个variable
Function<String, Purchase> abcFunction = doSomething();
然后像这样调用这个 importItemsFromFile() 函数
importItemsFromFile(items, filePath, abcFunction);
这样做的原因是,lambda 运算符返回一个函数接口,这里是“函数”,如果传递 3 个参数,则需要一个BiFunction<T, U, R>
。
这就是为什么这些 FunctionalInterfaces 有时被称为超级私有函数的原因,因为它们在另一个函数中使用。
嘿,给我加分,因为我什至完成了你写了一半的功能,节省了你 3 天的时间。
我对上面的代码片段有点迷惑,但您需要做的就是定义Function接口的实现。 您可以通过定义一个实现接口的类来简单地做到这一点,或者您可以指定一个可以做同样事情的 lambda。
假设最上面的代码块是你想要在你的 Lambada 中的代码块,你会做这样的事情,
(textLine) ->{
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(
products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
return new Purchase(
products.get(foundBarcode),
Integer.parseInt(purchases[1].trim())
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.