Given a non-empty ArrayList, what's the most elegant way to loop through rest elements while iterating that list ?
Give an ArrayList instance 'exampleList' contains five strings: ["A", "B", "C", "D", "E"]
while looping through it:
for(String s : exampleList){
// when s is "A", I want to loop through "B"-"E", inside this loop
// when s is "B", I want to loop through "C"-"E", inside this loop
// when s is "C", I want to loop through "D"-"E", inside this loop
}
Best way would probably be using the traditional for loop :
for (int i=0; i<exampleList.size(); i++) {
String s = exampleList.get(i);
for (int j=i+1; j<exampleList.size(); j++) {
String other = exampleList.get(j);
}
}
well i agree with @Eran answer traditional for loop but i give my try with iterator
List<String> exampleList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
Iterator<String> iterator = exampleList.iterator();
while (iterator.hasNext()) {
int start=exampleList.indexOf(iterator.next());
List lst = exampleList.subList(start,exampleList.size());
for(int i=0; i< lst.size() ; i++)
System.out.println(lst.get(i));
}
}
You can use stream's skip()
as well , makes for good looking code.
List<String> coreModules = new ArrayList<String>(Arrays.asList("A","B","C","D"));
for(int a=0;a<coreModules.size();a++){
coreModules.stream().skip(a).forEach(item -> System.out.println(item));
}
Though requires java 1.8,but looks elegent.
Here is the doc for stream
which has many such useful filter.
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.