membersound :
It is possible to pass a lambda expression as a function parameter? Example as follows: I want to pass the "strategy" that extracts properties from list items. For not having to repeat the stream mapping over and over again.
List<MyObject> list;
list.stream().map(item -> item.field1)).collector(Collectors.joining(","));
list.stream().map(item -> item.field2)).collector(Collectors.joining(","));
list.stream().map(item -> {
//some complex parser function
})).collector(Collectors.joining(","));
...
//pseudocode
private String map(List<MyObject> list, Function func) {
return list.stream.map(item -> func.call()).collector(Collectors.joining(","));
}
Update:
what if the object type changes? I still want to have my general map()
method that defines the collecting of the extracted field. But as the object type changes, I just want to supply a function that knows how to extract the desired property.
class Person {
String name;
}
class Car {
String manufacture;
}
map(persons, (person) -> person.name));
map(cars, (car) -> car.manufacture));
map(cars, (MyObject) -> {
//more complex parsing
}));
Ousmane D. :
use a Function<MyObject, String>
:
private String map(List<MyObject> list, Function<MyObject, String> func) {
return list.stream().map(func).collect(Collectors.joining(","));
}
Update:
here is a generic implementation:
private <T> String map(List<? extends T> list,
Function<? super T, ? extends CharSequence> func) {
return list.stream().map(func).collect(Collectors.joining(","));
}