I think fundamentally the code is correct. I would check your inputs and make sure they're really what you think.

I would perhaps rewrite your loop as:

for (String s : contain) {
   if (s.contains(code)) {
      // found it
   }
}

to make use of the object iterators (the above assumes you have an ArrayList<String>). And perhaps rename contain. It's not very clear what this is.

Answer from Brian Agnew on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_howto_loop_through_arraylist.asp
Java How To Loop Through an ArrayList
if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch ... For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays
Discussions

For-each loop ArrayList
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List. More on reddit.com
๐ŸŒ r/learnjava
6
11
April 4, 2023
How to fill out an ArrayList with for each loop? (Java) - Stack Overflow
I have to fill in an ArrayList with the first 10 multiples of two using a for each loop. I really can't seem to figure out how and I can't use any other loops. Here is my code which is not working... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is it possible to iterate over a std.array_list with a for loop ?
You can use the .toSlice() method on the ArrayList. Here's how you would do it with your example: const std = @import("std"); const allocator = std.debug.global_allocator; const warn = std.debug.warn; pub fn main() !void { const Vec32 = std.ArrayList(i32); var ages = Vec32.init(allocator); try ages.append(1); try ages.append(2); try ages.append(3); for (ages.toSlice()) |age| { warn("age: {}\\n", age); } } Keep in mind that .toSlice() returns a, well, slice into the ArrayList. If you want the slice to persist even after the ArrayList is deallocated, use .toOwnedSlice(), which will actually copy the data. More on reddit.com
๐ŸŒ r/Zig
10
7
May 14, 2019
Beginner Java Question: ArrayList - foreach into for loop with i-variable
You're getting foreach loops (sample solution) and for loops confused. The foreach loop looks like for (Software softwareprogram: softwareprograms) What this does is to go through each element of the softwareprograms list, and assign it to the variable, softwareprogram. This is something Java does for you. What do you lose? You don't have access to the index, so if you need to refer to some other element in a list, there's not a clean way to do it, and you would use a standard loop. In your version, you use a standard for loop, as in for (int i = 0; i < softwareprograms.size(); i++) } // Code to use softwareprogram } Java really isn't doing anything for you. You may think "I am processing a list, so Java should create special variables to help me out". Nope, in a way, it's basically like saying for (int i = 0; i < 10; i++) { I don't have a list at all. Java isn't going to be clever and say, the prior version has a list, and it will magically create a variable (which it doesn't as all variables need to be declared). You didn't declare softwareprogram. Instead, you have to do something like for (int i = 0; i < softwareprograms.size(); i++) } Software softwareprogram = softwareprograms.get(i); // Now do the rest of the code } foreach loops have support for lists (in that it knows how to process them) while plain for loops don't. It's a more mechanical process of accessing the items from the list. More on reddit.com
๐ŸŒ r/learnprogramming
19
0
January 13, 2021
People also ask

Why do we use forEach in Java?
It is a concept used to โ€œtraverseโ€ the ArrayList or a particular data set. It benefits the code by eliminating all possible bugs and making it more concise, robust, and readable.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ java arraylist foreach
Java ArrayList forEach - upGrad
What is the primary difference between forEach and for loop?
While the forEach loop works inside a specified range or collection of data, the for loop is applicable globally and is not restricted to a specific list or collection elements alone.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ java arraylist foreach
Java ArrayList forEach - upGrad
Can forEach transform elements in an array?
No, the Java forEach array method is primarily used to loop through the elements of the array. To transform them, you can use the MAP() function instead.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ java arraylist foreach
Java ArrayList forEach - upGrad
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ csawesome โ€บ Unit7-ArrayList โ€บ topic-7-3-arraylist-loops.html
7.3. Traversing ArrayLists with Loops โ€” CSAwesome v1
You can put any kind of objects into an ArrayList. For example, here is an ArrayList of Students. Although the print statement works here, you may want a nicer printout. Add a for each loop that prints out each student and then a new line.
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ csjava โ€บ Unit8-ArrayList โ€บ topic-8-3-arraylist-loops.html
8.3. Traversing ArrayLists with Loops โ€” CS Java
For example, if the word array is [โ€œHiโ€, โ€œthereโ€, โ€œTylerโ€, โ€œSamโ€], this figure shows how the word pairs are formed. In the class WordPairsList below, you will write the constructor which takes the array of words and pairs them up as shown in the figure.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ for-each loop arraylist
r/learnjava on Reddit: For-each loop ArrayList
April 4, 2023 -

I am in the third part of a MOOC course on Java. And I'm a little confused about the ambiguity of using the For-each loop to enumerate a list.

Consider the following list as an example

ArrayList<Integer> list = new ArrayList<>();

The examples and answers present two implementations:

for (Integer val: list) {

//do something

}

for (int val: list) {

//do something

}

But it is not explained how one differs from the other and when one or the other variant should be used. Please tell me the difference between the two.

Top answer
1 of 3
13
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List.
2 of 3
1
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 - best also formatted as code block 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. 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/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) 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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ iterating-arraylists-java
Iterating over ArrayLists in Java - GeeksforGeeks
import java.util.*; class GFG { ... Declaring object of integer type List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Iterating using for loop for (int i = 0; i < numbers.size(); i++) // Printing and display ...
Published ย  January 19, 2026
Find elsewhere
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ iterate-over-arraylist
Java Program to Iterate over an ArrayList
... import java.util.ArrayList; ... System.out.println("Iterating over ArrayList using for loop: "); for(int i = 0; i < languages.size(); i++) { System.out.print(languages.get(i)); System.out.print(", "); } } }...
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ java arraylist foreach
Java ArrayList forEach - upGrad
2 weeks ago - It eliminates manual index management and enhances code readability by offering a concise syntax. With forEach(), you can easily perform actions on each element of the ArrayList, making it ideal for processing data collections. This method simplifies complex operations and reduces the likelihood of errors with traditional for loops.
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2013 โ€บ 12 โ€บ how-to-loop-arraylist-in-java
How to loop ArrayList in Java
In this post we are sharing How to loop ArrayList in Java.There are four ways to loop ArrayList: For Loop, Advanced for loop, While Loop and Iterator..
๐ŸŒ
Medium
medium.com โ€บ @YodgorbekKomilo โ€บ day-12-for-each-loop-arraylist-in-java-7802d97b799c
Day 12 โ€” For-each Loop & ArrayList in Java | by Yodgorbek Komilov | Medium
December 24, 2025 - The real power comes when you combine ArrayList with a for-each loop: clean, readable code for dynamic lists.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java collections โ€บ enhanced for loop in java
Enhanced for loop in Java
February 13, 2025 - Alice Bob Charlie In this example, we create an ArrayList of Strings called names and add some values to it. We then use the enhanced for loop to iterate over the names ArrayList and print out each element.
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ java โ€บ arraylist โ€บ .foreach()
Java | ArrayList | .forEach() | Codecademy
April 13, 2025 - The .forEach() method performs a specified action on each element of the ArrayList one by one.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ loop-through-an-arraylist-using-an-iterator-in-java
Loop through an ArrayList using an Iterator in Java
import java.util.ArrayList; import ... aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (Iterator iter = aList.iterator(); iter.hasNext();) { System.out.println(iter.next()); } } }...
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_arraylist.asp
Java ArrayList
if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch ... For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2012 โ€บ 03 โ€บ how-to-loop-arraylist-in-java-code.html
5 Ways to Loop or Iterate over ArrayList in Java?
Iterator<String> iterator = loopList.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } Also by using Iterator approach for looping ArrayList you can remove element from ArrayList without fear of ConcurrentModific...
๐ŸŒ
Medium
medium.com โ€บ @reetesh043 โ€บ how-to-iterate-arraylist-in-java-with-examples-c66be52c8211
How to Iterate ArrayList in Java with Examples | by Reetesh Kumar | Medium
January 7, 2024 - In this example, we create a list of bank accounts and then use two ListIterator instances: one to iterate forward and another to iterate backward. The forward iterator traverses the list using next() and the backward iterator uses previous(). ...
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ java-for-each-loop-arraylist
Java For-Each Loop with ArrayList: A Comprehensive Guide โ€” javaspring.net
In this example, the for-each loop is used to iterate over an ArrayList of integers and calculate their sum. The for-each loop is best used for read-only operations on an ArrayList.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ collections framework โ€บ java arraylist โ€บ different ways to iterate an arraylist
Different Ways to Iterate an ArrayList
January 12, 2023 - ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") ); int index = 0; while (namesList.size() > index) { System.out.println(namesList.get(index++)); } Java program to iterate through an ArrayList of ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 11, 2025 - Example 1: Here, we will use the forEach() method to print all elements of an ArrayList of Strings. ... // Java program to demonstrate the use of forEach() // with an ArrayList of Strings import java.util.ArrayList; public class GFG { public ...