Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through list in java using for loop

How does one iterate through a list datastructure using indices. For example consider a sentence in form a list with each element being a word. Can I step through each word using the index? Something like this --

// sentence defined something like this - List<String>
int size = sentence.size();
for (int i=0; i<size-1; i++)
{
    System.out.println(sentence[i] + " " + sentence[i+1]);
}

ofcourse the above code doesn't work but is it possible to do something on those lines? As you can see, I want to access the two consecutive elements and using iterators, it starts becoming really messy.

like image 432
shashydhar Avatar asked Sep 13 '26 09:09

shashydhar


1 Answers

You can use the get(i) method instead of [i]:

for (int i=0; i<size-1; i++) {
    System.out.println(sentence.get(i) + " " + sentence.get(i+1));
}
like image 76
Sergey Kalinichenko Avatar answered Sep 15 '26 21:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!