I'm kind of new to generics in Java and I've faced such a problem: Let's say you have your own List implementation and you want to provide a mechanism to simultaneously convert all elements using some kind of mapping (functional interface) and collect them into a new list.
While the idea and use of functional interface (IMapper in my case) is straightforwad I can't quite think of what signature a function performing mapping should have?
Here's a little use case example and what I thought of as well. It does not work unfortunately and I guess the main problem is: How the second V param type should be passed in such case?
public interface IMapper<T,V> { V map(T v); }
public class MyList<T> extends ArrayList<T> {
public MyList<V> map(IMapper <T,V> mapper) {
MyList<V> list = new MyList<>();
for(T v : this) {
list.add(mapper.map(v));
}
return list;
}
}
// in main
MyList<Integer> list1 = new MyList<>();
// fill etc..
IMapper<Integer,String> m = (i) -> { return i.toString(); };
// "Change" list
MyList<String> list2 = list1.map(m);
PS:
I think that such thing is most probably already implemented in Java (stream() and what follows I guess?) however it suppose to be exercise for me. Any tip would be much appreciated :)