我正在嘗試實作一個函式來讀取檔案,但我無法更改該方法的簽名。代碼中有很多交叉參考,但也許有人可以啟發我,我現在已經卡住了 3 天。這是一個學校作業。
我試圖傳遞給函式的第一種方法如下:
public static Purchase fromLine(String textLine, List<Product> products) {
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
uj5u.com熱心網友回復:
您需要先在“超級私有函式”中像這樣宣告
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 天的時間。
uj5u.com熱心網友回復:
我對上面的代碼片段有點迷惑,但您需要做的就是定義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())
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330893.html
