So I am currenty trying to implement a method which does some filtering on lists regardless of their actual type. Here is the actual method:
public static <T extends List<String>> T filterList(T list, Predicate <String> predicate) {
T newList = ???
list.forEach(s -> {
if (predicate.test(s)) newList.add(s);
});
return newList;
}
So the generic type T is basically the some implementation of List such as ArrayList or LinkedList and regardless of their actual implementation I want to do some filtering through a Predicate passed as parameter. The return type of the method is the same as the list which is passed as a parameter. But how is it possible to instanciate an empty List based on T (see line 2)? To show you how the method is intended to be used i provided an example. The following example would filter an ArrayList based on the length of the containing Strings:
ArrayList<String> listOfNames = new ArrayList<>();
listOfNames.add("stackoverflowuser");
listOfNames.add("sitaguptana");
listOfNames.add("nyan cat");
listOfNames.add("pedro");
Predicate<String> lengthUnderTen = (string) -> string.length() < 10;
ArrayList <String> result = filterList(listOfNames,lengthUnderTen);