I am trying to compare two ArrayLists (i.e. ArrayList, list1 and ArrayList) testQueryValueand return the common elements between them. Below is what I have tried
private List<Loading> matchLists(List<Loading> list1 ,List<Test> list2) {
List<Loading> matchCriteria = new ArrayList<Loading>(list1);
List<String>testQueryValue= list2.get(0).getTestQueryValues();
for(Loading match: list1) {
for(Sring test: testQueryValue){
if (matchCriteria.contains(test)) {
matchCriteria.add(test); // Error: The method add(Loading) in the type List<Loading> is not applicable for the arguments (String)
}
}
return matchCriteria;
}
After editing this code as above getting the error as in the commented line in the code.
I know this question has already been asked several times. Based on the answers I have tried this approach and am unable to return the match. I am iterating through each elements of list1 which is a List of Loading, it contains nested arrays,and check if any element has test (subset of testQueryValue) in it? Then add test as the last element of matchCriteria which the method returns.
Thanks in advance for the help
matchCriteriathat could return anything or that could benull. Do you mean the list is empty? ( Due to you usingcontains(match)it should never containnulldirectly).MatchCriteria,getList2QueryValues()etc. don't seem to be JDK classes, so what library are you using? You need to elaborate, add some example input and required output and ideally provide a minimal reproducible example.List<String>orList<Loading>does your method return?matchCriteria.add(test);but would need to create aLoadinginstance out oftest(how that works depends on the same things as I stated above). Assuming there's aLoading(String)constructor and good implementations ofequals()andhashCode()you could do something likeLoading testLoading = new Loading(test); if( !matchCriteria.contains(testLoading) ) { matchCriteria.add(testLoading); }- or better yet, use aSet(LinkedHashSetif you need to preserve order) since this would already handle duplicates, so no need for a!contains()check.