I'm trying to create an equivalent to Javascript's Array#map in Java.
I have been able to do it with
ArrayList<String> data = myList.stream().map(e -> {
return "test "+e;
}).collect(Collectors.toCollection(ArrayList::new));
Here, myList is the initial ArrayList and data is the resulting ArrayList.
However, I find it very tedious to do that every time.
So I tried to create a generic function that would make my life easier :
public static ArrayList<?> map(ArrayList<?> list, Function<? super Object,?> callback){
return list.stream().map(callback).collect(Collectors.toCollection(ArrayList::new));
}
And then calling it with:
ArrayList<String> data = DEF.map(myList,e -> {
return "test "+e;
});
But I get the error
[Java] The method map(ArrayList, Function) in the type DEF is not applicable for the arguments (List, ( e) -> {})
How can I edit my generic function to accept the lambda I'm using?
Listvs.ArrayList. You should program to interfaces, i.e. change the parameter toList<?>.