简体   繁体   English

Java 传递带有两个参数的 (lambda) 函数

[英]Java passing a (lambda) function with two arguments

I'm trying to implement a function to read files, but I cannot change the signature of the method.我正在尝试实现一个函数来读取文件,但我无法更改该方法的签名。 There are a lot of cross references in the code but maybe someone can enlighten me, I have been stuck for 3 days right now.代码中有很多交叉引用,但也许有人可以启发我,我现在已经卡住了 3 天。

The first method I'm trying to pass into the function is the following:我试图传递给函数的第一种方法如下:

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

Somehow I want to pass this function into my import file function.不知何故,我想将此函数传递到我的导入文件函数中。

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

I hope someone can help me and explain how to pass this function into the other function's converter parameter.我希望有人可以帮助我并解释如何将此函数传递给另一个函数的转换器参数。 Tried to do a lot of research on this topic but I'm still not able to find the answer.试图对这个主题进行大量研究,但我仍然无法找到答案。 Please help me stackoverflow community!:D请帮助我stackoverflow社区!:D

You need to declare this like this first inside a 'super - private function'您需要先在“超级私有函数”中像这样声明

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

Then before calling this importItemsFromFile() method, you declare this function as a variable然后在调用这个 importItemsFromFile() 方法之前,将这个函数声明为一个variable

Function<String, Purchase> abcFunction = doSomething();

and then call this importItemsFromFile() function like this然后像这样调用这个 importItemsFromFile() 函数

importItemsFromFile(items, filePath, abcFunction);

The reason why this works is, lambda operator returns a Functional Interface, here it is "Function", if you pass 3 arguments, you will need a BiFunction<T, U, R> for that.这样做的原因是,lambda 运算符返回一个函数接口,这里是“函数”,如果传递 3 个参数,则需要一个BiFunction<T, U, R>

Thats why these FunctionalInterfaces are sometimes called super private functions, as they are used inside another function.这就是为什么这些 FunctionalInterfaces 有时被称为超级私有函数的原因,因为它们在另一个函数中使用。

And Hey give me extra points for this, as I even completed your half written function, and saved your 3 days time.嘿,给我加分,因为我什至完成了你写了一半的功能,节省了你 3 天的时间。

I am a little lost by the top snippet, but all you need to do is define an implementation of the Function interface.我对上面的代码片段有点迷惑,但您需要做的就是定义Function接口的实现。 You can do this simply by defining a class that implements the interface or you can specify a lambda that would do the same thing.您可以通过定义一个实现接口的类来简单地做到这一点,或者您可以指定一个可以做同样事情的 lambda。

Assuming the top code block is what you want in your lambada you would do something like this,假设最上面的代码块是你想要在你的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM