Reputation: 2987
I created the following interface:
public interface ConverterInterface<T, S> {
T convert(String id, S record, String event);
}
And All my Converter classes are implementing this one. Let's say I have multiple converters A, B, C, D...
For each class implementing this interface, I have a very similar load method like this:
private void loadA(String id, List<myObjA> objA, String event) {
if (objA == null) {
return;
}
// This is one class that implements that interface (I have multiple classes like this)
MyConverterA converter = ...
// Run over elements, call the converter and save it into an output list
for (myObjA record : objA) {
OUTPUT_LIST_A.add(converter.convertToEntity(id, record, event));
}
}
private void loadB(...) { ... }
private void loadC(...) { ... }
My goal is to convert this several load methods into a generic one so I can use the same according to my input.
I'm trying something like this:
private <S, T, V> void load (String id, List<S> data, T converter, List<V> output, String event) {
if (data == null) {
return;
}
for (S record: data) {
// Here I need to call the convert method from the interface
output.add()
}
}
Any ideas?
Thank you!
Upvotes: 0
Views: 51
Reputation: 7795
If you want to pass the List in:
private <S, T> void load (String id, List<S> data, ConverterInterface<T, S> converter, List<T> output, String event) {
if (data == null)
return;
for (S record: data)
output.add(converter.convert(id, record, event));
}
Otherwise, if you only pass in the input, you can use the Stream API and map
:
private <S, T> List<T> load (String id, List<S> data, ConverterInterface<T, S> converter, String event) {
if (data == null)
return Collections.emptyList();
return data.stream()
.map(record -> converter.convert(id, record, event))
.collect(toList());
}
The Point is that you only need two generic parameters, S
and T
and can specify Converter<S,T>
as a parameter type (add variance if you need to).
Upvotes: 1