This post talks about different options available for iterating over a List.
- using iterator - Jdk 1.2
List listItems = new LinkedList();
listItems.add("a");
. . .
listItems.add(n);
Iterator itr = listItems.iterator();
while(itr.hasNext()) {
String item = itr.next();
doSomething(item);
}
Supplier < Stream < String >> streamSupplier = () -> Stream.of("a", "b", "c");
listItems.add("a");
. . .
listItems.add(n);
Iterator itr = listItems.iterator();
while(itr.hasNext()) {
String item = itr.next();
doSomething(item);
}
- using for loop - Jdk 1.5
for(String item: listItems) {
doSomething(item);
}
- using for...each loop - Jdk 1.8
listItems.forEach(item -> doSomething(item));
- using Streams - Jdk 1.8
listItems.stream().filter(something).map(item -> doSomething(item)).count();
or
Stream.of("a", "b", "c").filter(something).map(item -> doSomething(item)).count();
Please note that the Streams can not be reused once it is done with any terminal operations. When you try to reuse you will get IlleagalStateException as the stream is already operated and closed.
If you want to reuse and avoid this exception then you may keep the above statement local scope or create a new stream every time using stream Supplier as below.
Supplier < Stream < String >> streamSupplier = () -> Stream.of("a", "b", "c");