If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line

!Collections.disjoint(list1, list2);

If you need to test a specific property, that's harder. I would recommend, by default,

list1.stream()
   .map(Object1::getProperty)
   .anyMatch(
     list2.stream()
       .map(Object2::getProperty)
       .collect(toSet())
       ::contains)

...which collects the distinct values in list2 and tests each value in list1 for presence.

Answer from Louis Wasserman on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java list › check if a list contains an element from another list in java
Check if a List Contains an Element From Another List in Java | Baeldung
May 7, 2025 - We’ll explore various ways how to achieve it using Java Streams, Collections disjoint(), and Apache Commons. The simplest version of this problem is if we want to check if an element in one List is equivalent to one in another. This could be primitive values or objects, assuming we’ve set up our objects to be compared.
Top answer
1 of 2
4

Your code is more complicated than it needs to be, but it gets the job done.

The awkward part of your code is the use of the various index values i, j, and k. Really, you don't need them at all. If you rename things a bit, and use "enhanced-for" loops, it becomes:

public boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {

    for(String title : titleOfVehicles) {
        boolean found = false;
        for(String model : models) {
            if(title.contains(model)) {
                found = true;
                break;
            }
        }
        if (!found) {
            return false;
        }
    }    
    return true;
}

Note that the logic is essentially the same, but you focus on the important things. The found variable is a better name, and it's scope is limited to inside the outer for-loop. The hard-to-understand k loop-terminator is removed.

Note, using streams, and a regular expression, would actually be more compact solution, but may not be as readable... I played with the stream version and a regex, and got:

public static boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {

    String pattern = models.stream()
          .map(Pattern::quote)
          .collect(Collectors.joining("|", ".*(", ").*"));

    Pattern re = Pattern.compile(pattern);

    return titleOfVehicles.stream()
        .allMatch(t -> re.matcher(t).matches());

}

(which you can see working here: https://ideone.com/8sqKu7 )

2 of 2
5

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 && 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<String> models, List<String> 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.

🌐
TutorialsPoint
tutorialspoint.com › how-to-check-if-java-list-contains-an-element-or-not
How to check if Java list contains an element or not?
May 9, 2022 - The Java LinkedList contains(Object) method returns true if this list contains the specified element. The object should have implemented equals() method in order to make this operation successful.
🌐
LabEx
labex.io › tutorials › java-how-to-check-if-a-list-contains-all-elements-of-another-list-in-java-559946
How to Check If a List Contains All Elements of Another List in Java | LabEx
Learn how to check if a Java list contains all elements of another list using containsAll() and manual loops. Master subset checks and handle empty/null lists effectively.
🌐
codestudy
codestudy.net › blog › check-if-one-list-contains-element-from-the-other
How to Efficiently Check if One List Contains Elements from Another List Based on a Specific Attribute in Java — codestudy.net
To efficiently check if one list contains elements from another based on a specific attribute: Avoid nested loops (O(n*m) complexity is too slow for large lists). Use a Set to store attributes from the second list (O(1) lookups). Leverage Java ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › list-containsall-method-in-java-with-examples
List containsAll() method in Java with Examples - GeeksforGeeks
December 11, 2018 - // Java code to illustrate containsAll() method import java.util.*; public class ListDemo { public static void main(String args[]) { // Creating an empty list List<Integer> list = new ArrayList<Integer>(); // Use add() method to add elements ...
Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › question › -java-list-check-elements
How to Efficiently Check If a Java List Contains Elements from Another List of the Same Type - CodingTechRoom
Leverage the HashSet to improve lookup speed: Convert one list to a set and then use the contains() method for the other list's elements.
🌐
Level Up Lunch
leveluplunch.com › java › examples › list-contains-any-elements
List contains any element - Java
January 30, 2014 - @Test public void list_contains_any_java () { // assuming 2013 boolean vehiclesFiveYearOrOlder = false; for (Vehicle vehicle : vehicles) { if ( (vehicle.year - 5) <= 2008) { vehiclesFiveYearOrOlder = true; break; } } assertTrue(vehiclesFiveYearOrOlder); } This snippet will check if any element in an arraylist matches a specified condition using java 8.
🌐
CopyProgramming
copyprogramming.com › howto › java-list-contains-any-from-another-list-java
Java: Checking if Java List contains any element from another List in Java
May 27, 2023 - It is possible for the function to return a true value as soon as a predicate-satisfying element is encountered. Using EnumSet.allOf(PermissionsEnum.class)::contains is a more efficient way as it outperforms List.contains due to its high level of efficiency, according to EnumSet.contains . list.stream().anyMatch(EnumSet.allOf(PermissionsEnum.class)::contains) A list contains at least one value from another list (Java 8), lambda - A list contains at least one value from another list (Java 8) - Stack Overflow A list contains at least one value from another list (Java 8) Ask Question 7 My function finds if from a list of given words at list one word is valid in the page.
🌐
Vultr
docs.vultr.com › java › standard-library › java › util › ArrayList › containsAll
Java ArrayList containsAll() - Check All Elements Presence | Vultr Docs
December 3, 2024 - The containsAll() method in Java's ArrayList class is a versatile tool for verifying the presence of all elements from one collection within another. By integrating this function into your Java applications, you enhance your ability to perform ...
🌐
JMP User Community
community.jmp.com › t5 › Discussions › How-to-check-if-a-list-contains-any-values-from-another-list › td-p › 829431
Solved: How to check if a list contains any values from another list? - JMP User Community
January 28, 2025 - Names Default To Here( 1 ); listA = {"a", "b", "c"}; listB = {"d", "c", "f"}; inBothList = {}; For Each( {member}, listA, If( Contains( listB, member ), Insert Into( inBothList, member ) ) ); Show( inBothList ); arrayA = Associative Array( listA ); arrayB = Associative Array( listB ); arrayA << intersect( ArrayB); show( arrayA );
🌐
TutorialsPoint
tutorialspoint.com › how-do-you-check-a-list-contains-an-item-in-java
How do you check a list contains an item in Java?
May 10, 2022 - Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ?
🌐
TutorialsPoint
tutorialspoint.com › how-do-you-check-if-an-element-is-present-in-a-list-in-java
How do you check if an element is present in a list in Java?
May 10, 2022 - The Java ArrayList contains(Object) method returns true if this list contains the specified element. The object should have implemented equals() method in order to make this operation successful.
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-contains-java
Arraylist.contains() Method in Java - GeeksforGeeks
December 10, 2024 - Returns: It returns true if the specified element is found in the list else it returns false. Example 2: Here, we are using the contains() method to check if the ArrayList of Integers contains a specific number.
🌐
Educative
educative.io › answers › what-is-the-arraylistcontainsall-method-in-java
What is the ArrayList.containsAll() method in Java?
The ArrayList.containsAll() method is used in line 18 to check if all the elements of list2 are present in list1. The ArrayList.containsAll() method returns false, which means that list1 does not contain all the elements in list2.
🌐
Baeldung
baeldung.com › home › java › java list › how to find an element in a list with java
How to Find an Element in a List with Java | Baeldung
September 19, 2025 - Java itself provides several ways of finding an item in a list: ... As the name suggests, this method returns true if the list contains the specified element, and returns false otherwise. So when we need to check if a specific item exists in our list, we can: Customer james = new Customer(2, "James"); if (customers.contains(james)) { // ... } indexOf is another useful method for finding elements: