Java, How to Get Current Index/Key in "For Each" Loop

Java, How do I get current index/key in for each loop

You can't, you either need to keep the index separately:

int index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}

or use a normal for loop:

for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}

The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"

Is there a way to access an iteration-counter in Java's for-each loop?

No, but you can provide your own counter.

The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).

Get the current index of a for each loop iterating an ArrayList

Just use a traditional for loop:

for (int i = 0; i < yourArrayList.size(); i ++) {
// i is the index
// yourArrayList.get(i) is the element
}

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
.forEach(idx ->
query.bind(
idx,
params.get(idx)
)
)
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

How do you get the index of the current iteration of a foreach loop?

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

The concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

Does JVM keeps track of index in foreach loop in Java? If so, How?

Depends.

There are two versions of this loop, for arrays and for Iterable (things like List).

For arrays, the compiler will create a "normal" for (int i=0; i<arr.length; i++) loop. So here you have that index.

For Iterable, it becomes while(iter.hasMore()){. So there is no index in the loop itself. Depending on the Iterable implementation, there may still be one inside the Iterator.

How would I loop through an array of objects and check for existence of key- or value parameter?

Your implementation of for...in loop is wrong, check the documentation here, for..in

Although you can use for..in loop for iterating over the array, important thing to note here from Mozilla docs is:-Documentation

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

var array = [{
name: 'Antonello',
location: 'Barcelona'
},
{
email: 'george@george.com',
name: 'George'
},
{
name: 'Mike',
coder: true
}
];

function getIndex(array, key, value) {
var indexFound = -1;
array.forEach((obj, index) => {
if (obj[key] !== undefined && obj[key] === value) {
indexFound = index;
}
});
return indexFound;
}

var foundIndex = getIndex(array, 'name', 'Antonello');
console.log(foundIndex);

Iterate Java Map with index

LinkedHashMap preserves the order in which entries are inserted. So you can try to create a list of the keys and loop using an index:

List<String> keyList = new ArrayList<String>(map.keySet());
for(int i = fromIndex; i < toIndex; i++) {
String key = keyList.get(i);
String value = map.get(key);
...
}

Another way without creating a list:

int index = 0;
for (String key : map.keySet()) {
if (index++ < fromIndex || index++ > toIndex) {
continue;
}
...
}

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
<li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>

Get loop counter/index using for…of syntax in JavaScript

for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

Or ES6’s Array.prototype.entries, which now has support across current browser versions:

for (const [i, value] of myArray.entries()) {
console.log('%d: %s', i, value);
}

For iterables in general (where you would use a for…of loop rather than a for…in), there’s nothing built-in, however:

function* enumerate(iterable) {
let i = 0;

for (const x of iterable) {
yield [i, x];
i++;
}
}

for (const [i, obj] of enumerate(myArray)) {
console.log(i, obj);
}

demo

If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.



Related Topics



Leave a reply



Submit