I am trying to combine two lists of different objects for simplicity ill refer to them as List<A>
and List<B>
and in the end sort the combined list by their date value. I've seen most of the answers here but they dont show the whole picture on how to properly implement such use case.
I have created an inferface with a String getDate()
method. So that my Class A
and Class B
both imeplement said interface.
public interface CustomInterface {
String getDate();
}
Then i have created a CustomComparator class:
public class CustomComparator implements Comparator<CustomInterface> {
@Override
public int compare(CustomInterfacet1, CustomInterface t2) {
return t1.getDate().compareTo(t2.getDate());
}
}
I also implemented a custom class which handles both the merge and sorting of the two given Lists.
We will call it Class Merge
. With the method implemented below.
public List<Object> sortedAndMergedData(List<A> a, List<B> b) {
List<Object> x= new ArrayList<>();
x.addAll(a);
x.addAll(b);
Collections.sort(x, new CustomComprator());
return x;
}
This is where the issue is, because im getting an error, "reason: no instance(s) of type variable(s) exist so that Object conforms to Interface" on Collections.sort(x, new CustomComprator());
CodePudding user response:
Change List<Object>
to List<CustomInterface>
in
List<Object> x= new ArrayList<>();
provided that both your A
and B
classes implements CustomInterface
public List<CustomInterface> sortedAndMergedData(List<A> a, List<B> b) {
List<CustomInterface> x= new ArrayList<>();
x.addAll(a);
x.addAll(b);
Collections.sort(x, new CustomComprator());
return x;
}