繁体   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