Is it possible to specify an index/range in enhanced for loop in Java?
For eg I have a list: List<String> list;
And I want to run a for loop from index 1 instead of 0:
for(String s : list(start from index 1))
OR till index 5
for(String s : list(end at index 5))
I know I can use traditional for loop or keep a counter inside the enhanced for loop but I wanted to know is there something out of the box in Java or apache collections?
I would use subList
in this case:
for(String s : list.subList(1, list.size()))
and
for(String s : list.subList(0, 6))
Using of sublist
is better but stream version is using skip
and limit
:
list.stream().skip(1) .... limit(6).....
In the Java 8 we have Stream API, which we could use to iterate over List with custom indexes:
List<String> evenIndexes = IntStream
.range(0, names.length)
.filter(i -> i % 2 == 0)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
in the range
method, you could start from 1, and/or iterate to 5.
The traditional for loop is the "out of the box" solution for this requirement:
for (int i = 1; i < list.size(); i++) {
String s = list.get(i);
...
}
and (if the List
has at least 5 elements):
for (int i = 0; i < 5; i++) {
String s = list.get(i);
...
}
I am not sure of the performance penalty, but you can use List::subList
List<String> list = Arrays.asList("a", "b", "c");
for (String s : list.subList(1, list.size())) {
System.out.println(s);
}
output
2
3
It is possible with list.subList(1, list.size())
, but it will add performance penalty for sublisting list. It is better to use traditional for loop in this case.
//Calculate size first to avoid performance penalty calculating in loop each iteration
int size = list.size();
for (int i = 1; i < size; i++) {
String s = list.get(i);
...
}
You can use it
for(int i=1 ; i< list.size ; i++){
String str = list.get(i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.