簡體   English   中英

java.util.ArrayList通過循環中的其余元素循環

[英]java.util.ArrayList loop through rest elements inside a loop

給定一個非空的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
}

最好的方法可能是使用傳統的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);
    }
}

好吧,我同意@Eran回答傳統的for循環,但是我嘗試使用迭代器

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

您也可以使用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,但是看起來很優雅。

stream的文檔,其中包含許多此類有用的過濾器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM