loops - Ways to iterate over a List in java? -
being new java language i'm trying familiarize myself ways (or @ least non-pathological ones) 1 might iterate through list (or perhaps other collections) , advantages or disadvantages of each.
given list<e> list
object, know of following ways loop through elements:
basic for loop (of course, there're equivalent while
/ do while
loops well)
// not recommended (see below)! (int = 0; < list.size(); i++) { e element = list.get(i); // 1 - can call methods of element // 2 - can use make index-based calls methods of list // ... }
note: @amarseillan pointed out, form poor choice iterating on list
s because actual implementation of get
method may not efficient when using iterator
. example, linkedlist
implementations must traverse of elements preceding i-th element. in above example there's no way list
implementation "save place" make future iterations more efficient. arraylist
doesn't matter because complexity/cost of get
constant time (o(1)) whereas linkedlist
proportional size of list (o(n)). more information computational complexity of built-in collections
implementations, check out this question.
enhanced for loop (nicely explained in question)
for (e element : list) { // 1 - can call methods of element // ... }
iterator
for (iterator<e> iter = list.iterator(); iter.hasnext(); ) { e element = iter.next(); // 1 - can call methods of element // 2 - can use iter.remove() remove current element list // ... }
edit: added listiterator
listiterator
for (listiterator<e> iter = list.listiterator(); iter.hasnext(); ) { e element = iter.next(); // 1 - can call methods of element // 2 - can use iter.remove() remove current element list // 3 - can use iter.add(...) insert new element list // between element , iter->next() // 4 - can use iter.set(...) replace current element // ... }
edit: added "functional-style" solution (thanks dave newton)
functional java
list.stream().map(e -> e + 1); // can apply transformation function e
edit: added map method java 8's stream api (see @i_am_zero's answer)
iterable.foreach, stream.foreach, ...
in java 8 collection classes implement iterable
(for example list
s) have foreach
method, can used instead of for loop statement demonstrated above. (here another question provides comparison.)
arrays.aslist(1,2,3,4).foreach(system.out::println); // 1 - can call methods of element // 2 - need reference containing object remove item // (todo: please confirm / deny this) // 3 - functionally separates iteration action // being performed each item. arrays.aslist(1,2,3,4).stream().foreach(system.out::println); // same capabilities above plus potentially greater // utilization of parallelism // (caution: consequently, order of execution not guaranteed, // see [stream.foreachordered][stream-foreach-ordered] more // information this.)
what other ways there, if any?
i feel has got duplicate, haven't been able find i'm looking for, apologize question potentially being redundant. (btw, interest not stem @ desire optimize performance; want know forms available me developer.)
edit: moved listiterationexample.java suggested answer
the 3 forms of looping identical. enhanced for
loop:
for (e element : list) { . . . }
is, according java language specification, identical in effect explicit use of iterator traditional for
loop. in third case, can modify list contents removing current element, , if through remove
method of iterator itself. index-based iteration, free modify list in way. however, adding or removing elements come before current index risks having loop skipping elements or processing same element multiple times; need adjust loop index when make such changes.
in cases, element
reference actual list element. none of iteration methods makes copy of in list. changes internal state of element
seen in internal state of corresponding element on list.
essentially, there 2 ways iterate on list: using index or using iterator. enhanced loop syntactic shortcut introduced in java 5 avoid tedium of explicitly defining iterator. both styles, can come trivial variations using for
, while
or do while
blocks, boil down same thing (or, rather, 2 things).
edit: @ix3 points out in comment, can use listiterator
set current element of list iterating. need use list#listiterator()
instead of list#iterator()
initialize loop variable (which, obviously, have declared listiterator
rather iterator
).
Comments
Post a Comment