

The custom code specified inside the For-each loop will be executed for each element. The : in the syntax can be read as in: For each element IN the list. T describes the data type of the elements Item represents each element of the array/collection It makes the loop more concise and easy to read.Įlements_of_type_T denotes a collection or an array The code of For-each is compact, straightforward, and easy to understand. The following is the general syntax of an enhanced for loop: for (T item : elements_of_type_T) The concept of For-each is mainly introduced in Java 5 to provide a concise and convenient way to iterate over arrays and collections in a fail-safe manner.

Enhanced For Loop in Javaīefore diving deep into the details, please bear in mind that an enhanced for loop is called also For-each in Java. Then, we will exemplify its use through practical examples. In this article, we are going to put the focus on Java enhanced for loop.įirst, we will shed light on what an enhanced for is in Java.

For mutable lists, the standard library offers similar extension functions that perform the same ordering operations in place. In Collection Ordering, we describe operations that retrieve collection elements in specific orders. Val numbers = mutableListOf(1, 2, 3, 4, 3) You can also specify an index range to search in: in this case, the function searches only between two provided indices. If there is more than one element with the given value, the search can return any of their indices.

If such an element exists, the function returns its index otherwise, it returns (-insertionPoint - 1) where insertionPoint is the index where this element should be inserted so that the list remains sorted. To search an element in a sorted list, call the binarySearch() function passing the value as an argument. It works significantly faster than other built-in search functions but requires the list to be sorted in ascending order according to a certain ordering: natural or another one provided in the function parameter. There is one more way to search elements in lists – binary search.
