Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 778
Prasad Avatar asked Nov 29 '18 14:11

Prasad


2 Answers

Use a lambda expression:

names.stream().map(name -> MyClass.createReport(name,designation))...
like image 149
Eran Avatar answered Nov 11 '22 20:11

Eran


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))
like image 23
Roman Avatar answered Nov 11 '22 18:11

Roman