Verifying if one list contains a string from another list I am trying to validate that when given two lists,

List&lt;String&gt; models;
List&lt;String&gt; 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&lt;String&gt; models, List&lt;String&gt; titleOfVehicles) {
    boolean flag = false;

    for(int i = 0; i &lt; titleOfVehicles.size(); i++) {
        flag = false;
        int k = 0;
        for(int j = 0; j &lt; models.size(); j++) {
            if(titleOfVehicles.get(i).contains(models.get(j))) {
                flag = true;
                break;
            } else if(k == models.size() - 1 &amp;&amp; flag == false) {                        
                return false;
            }    
            k++;
        }
    }    
    return flag;
}
The current code works but it is very awkward, as rolfl pointed out. I would add that you should never compare booleans with true or false, like what you're doing in:

} else if(k == models.size() - 1 &amp;&amp; flag == false) {                        
    return false;
}


Instead, have

} else if (k == models.size() - 1 &amp;&amp; !flag) {                        
    return false;
}




You can actually accomplish this task in a single, clear and easy line using the Stream API:

public boolean compareTwoList(List&lt;String&gt; models, List&lt;String&gt; titleOfVehicles) {
    return titleOfVehicles.stream().allMatch(t -&gt; 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.