java.util.ArrayList遍历循环中的rest元素

时间:2015-04-04 16:17:47

标签: java

给定一个非空的ArrayList,在迭代该列表时循环遍历rest元素的最优雅方法是什么?

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
}

3 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

我同意@Eran回答传统for循环,但我尝试使用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));
    }
 }

答案 2 :(得分: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,但看起来很优雅。

Herestream的文档,其中包含许多此类有用的过滤器。