There are a few ways.

Which one you choose is up to you, there's a tradeoff between verbosity, being constrained to a simple equals check (if you want to do more complicated matching, you can't easily do Option 1), and using newer APIs that you might not yet support or be familiar with.

Option 1: The Collection.contains() method:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

if (fruits.contains("banana") {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 2: Using a for loop with external state:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

boolean found = false;
for (String s : fruits) {
    if (s.equals("banana")) {
        found = true;
        break; // Break out of the loop to skip the remaining items
    }
}
if (found) {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 3: If you're using Java 8, the neat Stream.anyMatch() method:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

if (fruits.stream().anyMatch(s -> s.equals("banana"))) {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 3 is my personal favorite, as it's nearly as compact as Option 1, but allows to to provide a more complex Predicate if you want a comparison based on something other than the equals() method.

Answer from Craig Otis on Stack Overflow
Top answer
1 of 4
33

There are a few ways.

Which one you choose is up to you, there's a tradeoff between verbosity, being constrained to a simple equals check (if you want to do more complicated matching, you can't easily do Option 1), and using newer APIs that you might not yet support or be familiar with.

Option 1: The Collection.contains() method:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

if (fruits.contains("banana") {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 2: Using a for loop with external state:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

boolean found = false;
for (String s : fruits) {
    if (s.equals("banana")) {
        found = true;
        break; // Break out of the loop to skip the remaining items
    }
}
if (found) {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 3: If you're using Java 8, the neat Stream.anyMatch() method:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

if (fruits.stream().anyMatch(s -> s.equals("banana"))) {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 3 is my personal favorite, as it's nearly as compact as Option 1, but allows to to provide a more complex Predicate if you want a comparison based on something other than the equals() method.

2 of 4
2

You don't have to iterate through the array list. Once you call list.contains("someString"), it will check for that string in that entire array list. Therefore, the following is enough.

if(fruit.contains("banana"){
     System.out.println("Found");
} else {
     throw new SkipException("could not be found");
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › list-contains-method-in-java-with-examples
List contains() method in Java with Examples - GeeksforGeeks
December 3, 2024 - Program 2: Demonstrate the working of the method contains() in List of string. ... // Java code to demonstrate the working of // contains() method in List of string import java.util.*; class GFG { public static void main(String[] args) { // creating an Empty String List List<String> arr = new ArrayList<String>(4); // using add() to initialize values // ["geeks", "for", "geeks"] arr.add("geeks"); arr.add("for"); arr.add("geeks"); // use contains() to check if the element // "geeks" exits or not boolean ans = arr.contains("geeks"); if (ans) System.out.println("The list contains geeks"); else System.out.println("The list does not contains geeks"); // use contains() to check if the element // "coding" exits or not ans = arr.contains("coding"); if (ans) System.out.println("The list contains coding"); else System.out.println("The list does not contains coding"); } }
Discussions

How do I know if an array list contains an specific string
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
14
9
May 12, 2022
arrays - Java, return if trimmed String in List contains String - Stack Overflow
I want it to return true if my item 'B' is in the list. How should I do this? I would like to avoid a looping structure. ... AFAIK in vanilla JDK, no. I guess in Java 8 with closures you will achieve this in one line. ... how do i achieve it. without writing looping condition. In fact, it checks each string ... More on stackoverflow.com
🌐 stackoverflow.com
java - Check if a String is in an ArrayList of Strings - Stack Overflow
The List.contains() method checks for identity, not equality. It works well for integers but not strings (which is what OP asked for). Iterating over the list, or better, using Java8 List stream is the way to go for List 2017-07-16T23:53:10.967Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
java - Test if a string contains any of the strings from an array - Stack Overflow
Question is the opposite: Does the target string contain any of the list’s strings. 2016-05-16T23:40:30.337Z+00:00 ... @DilankaLaksiri not really, those methods have been available since Java 8. And the latest version of Java is 16, so what "API level 24" are you referring to? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › java › java list › check if a list contains a string element while ignoring case
Check if a List Contains a String Element While Ignoring Case | Baeldung
March 7, 2025 - In this quick tutorial, we’ll explore various methods and strategies to solve this common problem in Java. List provides the convenient contains() method to check if a given value exists in the list.
🌐
Reddit
reddit.com › r/javahelp › how do i know if an array list contains an specific string
r/javahelp on Reddit: How do I know if an array list contains an specific string
May 12, 2022 -

I created an array list out from a constructor, now what I want to do is that the program will only print those set of array list with the item that matches the search key. I tried using arraylist.contains but it won't work. Is there any method I can use to know whether the array contains a specific certain string? Thank you!

🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-contains-java
Arraylist.contains() Method in Java - GeeksforGeeks
July 18, 2026 - Explanation: In this example, an ArrayList of strings is created containing "Apple", "Blueberry", and "Strawberry". The contains() method first checks for "Grapes", which is not present, so it returns false. It then checks for "Apple", which ...
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-arraylist-contains-method-example
Java ArrayList contains() Method example
September 11, 2022 - Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java · ArrayList contains() method is used for checking the specified element existence in the given list. public boolean contains(Object element) It returns true if the specified element is found in the list else it gives false.
Find elsewhere
🌐
Codecademy
codecademy.com › docs › java › arraylist › .contains()
Java | ArrayList | .contains() | Codecademy
February 22, 2024 - Beginner Friendly.Beginner Friendly17 hours17 hours · The .contains() method can be called on an ArrayList instance and requires a single parameter: ... In the example below, an empty ArrayList instance fruitList is created, which can hold ...
🌐
Techie Delight
techiedelight.com › home › java › check if a string contains any of substrings from a list in java
Check if a string contains any of substrings from a List in Java | Techie Delight
July 7, 2026 - Alternately, you can filter elements with the filter() method to get the actual substring contained in the string, as shown below: ... Finally, you can leverage the Apache Commons Lang library, which provides the indexOfAny() method in the StringUtils class. It will return the first index of any of a set of given substrings, -1 for no match or null input. However, it accepts varargs, so you have to convert the list to a String array first, as shown below:
🌐
Mkyong
mkyong.com › home › java › java – how to search a string in a list?
Java - How to search a string in a List? - Mkyong.com
October 15, 2019 - In Java, we can combine a normal loop and .contains(), .startsWith() or .matches() to search for a string in ArrayList. ... package com.mkyong.test; import java.util.ArrayList; import java.util.List; public class JavaExample1 { public static ...
Top answer
1 of 16
270

EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.

public static boolean stringContainsItemFromList(String inputStr, String[] items) {
    return Arrays.stream(items).anyMatch(inputStr::contains);
}

Also, if we change the input type to a List instead of an array we can use items.stream().anyMatch(inputStr::contains).

You can also use .filter(inputStr::contains).findAny() if you wish to return the matching string.

Important: the above code can be done using parallelStream() but most of the time this will actually hinder performance. See this question for more details on parallel streaming.


Original slightly dated answer:

Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings. A primitive way to make it case insensitive would be to call toLowerCase() or toUpperCase() on both the input and test strings.

If you need to do anything more complicated than this, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions. Once you understand those, you can use those classes or the String.matches() helper method.

public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
    for(int i =0; i < items.length; i++)
    {
        if(inputStr.contains(items[i]))
        {
            return true;
        }
    }
    return false;
}
2 of 16
61
import org.apache.commons.lang.StringUtils;

String Utils

Use:

StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})

It will return the index of the string found or -1 if none is found.

🌐
Vultr
docs.vultr.com › java › standard-library › java › util › ArrayList › contains
Java ArrayList contains() - Check If Contains Element | Vultr Docs
November 27, 2024 - Use the contains() method to check if a specific element is present. ... import java.util.ArrayList; ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); boolean exists = list.contains("Banana"); ...
🌐
W3Schools
w3schools.com › JAVA › ref_arraylist_contains.asp
Java ArrayList contains() Method
Check if an item exists in a list: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars.contains("BMW")); System.out.println(cars.contains("Toyota")); } } Try it Yourself » ·
🌐
Stack Overflow
stackoverflow.com › questions › 75148997 › checking-if-a-list-of-lists-contains-a-certain-string
java - Checking if a List of Lists contains a certain String - Stack Overflow
The contains (Object o) method of List will search list looking to satisfy the condition e.equals (o), where e is an element in the List. "Nigeria" is a String, so will never equal an Object of type List. As the comment from @Jonxag said, you need to iterate through list and check each sublist. docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/…
🌐
CodingTechRoom
codingtechroom.com › question › check-list-contains-string-java
How to Determine if a List<String> Contains a Specific String in Java? - CodingTechRoom
List<String> myList = ... you can easily verify the presence of a specific string within a List<String> using the `contains()` method....
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.

🌐
Baeldung
baeldung.com › home › java › java list › searching for a string in an arraylist
Searching for a String in an ArrayList | Baeldung
April 4, 2025 - public List<String> findUsingLoop(String search, List<String> list) { List<String> matches = new ArrayList<String>(); for(String str: list) { if (str.contains(search)) { matches.add(str); } } return matches; } The Java 8 Streams API provides us with a more compact solution by using functional operations.