Ways to iterate over a list in Java

后端 未结 12 1849
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:46

Being somewhat new to the Java language I\'m trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or

12条回答
  •  遇见更好的自我
    2020-11-22 01:14

    In Java 8 we have multiple ways to iterate over collection classes.

    Using Iterable forEach

    The collections that implement Iterable (for example all lists) now have forEach method. We can use method-reference introduced in Java 8.

    Arrays.asList(1,2,3,4).forEach(System.out::println);
    

    Using Streams forEach and forEachOrdered

    We can also iterate over a list using Stream as:

    Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
    Arrays.asList(1,2,3,4).stream().forEachOrdered(System.out::println);
    

    We should prefer forEachOrdered over forEach because the behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept.

    The advantage with streams is that we can also make use of parallel streams wherever appropriate. If the objective is only to print the items irrespective of the order then we can use parallel stream as:

    Arrays.asList(1,2,3,4).parallelStream().forEach(System.out::println);
    

提交回复
热议问题