patternjavaMinor
Verifying if one list contains a string from another list
Viewed 0 times
verifyingonecontainsanotherlistfromstring
Problem
I am trying to validate that when given two lists,
that one of the
For example, given the following:
then when comparing
Here is my code:
List models;
List titleOfVehicle;that one of the
models must be contained in each of the titleOfVehicle.For example, given the following:
models = {Accord, Civic, Element}
titleOfVehicle1 = {2014 Honda Accord, 2011 Toyota Camry}
titleOfVehicle2 = {2013 Honda Accord, 2015 Honda Element, 2011 Honda Civic}then when comparing
models and titleOfVehicle1 it will fail since 2011 Toyota Camry does not contain one of the models provided. However, titleOfVehicle2 will pass since it contains a model for each vehicle titles. Here is my code:
public boolean compareTwoList(List models, List titleOfVehicles) {
boolean flag = false;
for(int i = 0; i < titleOfVehicles.size(); i++) {
flag = false;
int k = 0;
for(int j = 0; j < models.size(); j++) {
if(titleOfVehicles.get(i).contains(models.get(j))) {
flag = true;
break;
} else if(k == models.size() - 1 && flag == false) {
return false;
}
k++;
}
}
return flag;
}Solution
The current code works but it is very awkward, as rolfl pointed out. I would add that you should never compare booleans with
Instead, have
You can actually accomplish this task in a single, clear and easy line using the Stream API:
This does exactly what is written: it returns whether all elements in the given titles contains any of the given models.
Both
true or false, like what you're doing in:} else if(k == models.size() - 1 && flag == false) {
return false;
}Instead, have
} else if (k == models.size() - 1 && !flag) {
return false;
}You can actually accomplish this task in a single, clear and easy line using the Stream API:
public boolean compareTwoList(List models, List titleOfVehicles) {
return titleOfVehicles.stream().allMatch(t -> models.stream().anyMatch(t::contains));
}This does exactly what is written: it returns whether all elements in the given titles contains any of the given models.
Both
allMatch and anyMatch are short-circuiting operations, so it will behave exactly like your current code.Code Snippets
} else if(k == models.size() - 1 && flag == false) {
return false;
}} else if (k == models.size() - 1 && !flag) {
return false;
}public boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {
return titleOfVehicles.stream().allMatch(t -> models.stream().anyMatch(t::contains));
}Context
StackExchange Code Review Q#134928, answer score: 5
Revisions (0)
No revisions yet.