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()?
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 eachname
is the same. Additionly we just need to call the not curried method.In Action
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:
What the JVM undertands
Solutions use a basic lamba as @Eran or a Function as @Roman suggested.
You could also use the following as an alternative:
Use a lambda expression: