Wednesday, January 15, 2025
HomeProgrammingIs there a Java equivalent of Python's 'enumerate' function?

Is there a Java equivalent of Python’s ‘enumerate’ function?

Java doesn’t have a direct enumerate function like Python, but you can achieve similar functionality. Using a simple for loop:

String[] fruits = {“Apple”, “Banana”, “Cherry”};
for (int i = 0; i < fruits.length; i++) { System.out.println("Index: " + i + ", Value: " + fruits[i]); } For lists, use IntStream:

See also  How to make HTML Text unselectable? [duplicate] - css
import java.util.List; import java.util.stream.IntStream; List fruits = List.of(“Apple”, “Banana”, “Cherry”);
IntStream.range(0, fruits.size()).forEach(i ->
System.out.println(“Index: ” + i + “, Value: ” + fruits.get(i))
);

Both methods provide the index and value while iterating through the collection.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x