Java 8 - Calling a multi argument method from Collection.stream.map()

走远了吗. 提交于 2019-12-10 04:13:37

问题


I've been using the java 8 Streams for a while. I came across a situation where I need to stream through a List and pass each element to a static method along with another argument. Is it possible in java 8?

........
String designation = "Engineer";
List<String> names = new ArrayList<>();
names.add("ABC");
names.add("DEF");
names.add("GHI");
names.stream().map(MyClass::createReport);
..........

class MyClass {
    public static void createReport(String name, String designation) {
       System.out.println(name+"\t"+designation);
    }
}

How can I pass the designation String via stream().map()?


回答1:


Use a lambda expression:

names.stream().map(name -> MyClass.createReport(name,designation))...



回答2:


You could write a curried version of the method createReport.

Curried createReport

We need to swap the order of the arguments because the designation for each name is the same. Additionly we just need to call the not curried method.

Function<String, Consumer<String>> createReportCurry = (designation) -> (name) -> {
    createReport(name, designation);
};

In Action

names.stream().forEach(createReportCurry.apply(designation))



回答3:


You could also use the following as an alternative:

IntStream.range(0, names.size())
         .forEach(i -> MyClass.createReport(names.get(i), names.get(i)));



回答4:


The above answer are very good but let's try to explain why you couldn't run your code in the first place:

Your code:

names.stream().map(MyClass::createReport);names.stream().map(MyClass::createReport);

What the JVM undertands

names.stream().map(MyClass::createReport);names.stream().map(name -> MyClass.createReport(name));

Solutions use a basic lamba as @Eran or a Function as @Roman suggested.



来源:https://stackoverflow.com/questions/53541030/java-8-calling-a-multi-argument-method-from-collection-stream-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!