2015-04-04 120 views
2

給定一個非空的ArrayList,迭代該列表時循環休息元素的最優雅方式是什麼?java.util.ArrayList通過循環內的休息元素循環

Give an ArrayList instance 'exampleList' contains five strings: ["A", "B", "C", "D", "E"] 

,同時通過它循環:

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 
} 

回答

4

最好的辦法可能是使用傳統的for循環:

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); 
    } 
} 
0

以及我@Eran同意接聽傳統的循環,但我給我用迭代器試試

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)); 
    } 
} 
0

您也可以使用stream's skip(),以獲得好看的代碼。

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)); 
    } 

雖然要求java 1.8,但看起來像elegent。

Herestream的文檔,它有很多這樣有用的過濾器。