While following a Java course I was asked to convert a regular class to a generic one. I think I partially succeeded but can'f find a way to get it 100% right.
public class ElementUtils {
public static <T> List transformedList(List<T> inList, Function<T, T> f) {
List<T> outList = new ArrayList<>();
for (T s : inList) {
outList.add(f.apply(s));
}
return outList;
}
}
Test class
public class Test {
public static void main(String[] args) {
List<String> lijst = Arrays.asList("Jan", "Jos", "Anna", "Pieter", "Johan");
List<String> upCaseList = ElementUtils.transformedList(lijst, String::toUpperCase);
List<String> replaceList = ElementUtils.transformedList(lijst, s -> s.replace("i", "IETS"));
List<String> exclList = ElementUtils.transformedList(lijst, s -> s + "!");
List<Integer> wordLengths = ElementUtils.transformedList(lijst, String::length);
System.out.println(upCaseList);
System.out.println(replaceList);
System.out.println(exclList);
System.out.println(wordLengths);
}
}
When I remove the last statement wordLengths
it works fine but throws a warning. With the last statement in it, it's telling ne that I cannot reference a method from a static content.
Error:
Error:(13, 49) java: method transformedList in class cvo.ex2.ElementUtils cannot be applied to given types;
required: java.util.List<T>,java.util.function.Function<T,T>
found: java.util.List<java.lang.String>,String::length
reason: inference variable T has incompatible bounds
equality constraints: java.lang.String
lower bounds: java.lang.Integer
I don't understand what I'm missing here... Thank you for your help.