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 perhaps other collections) and the advantages or disadvantages of each.
(对Java语言有些陌生,我试图使自己熟悉所有可能遍历列表(或其他集合)的方式(或至少是非病理性方式)以及每种方式的优缺点。)
Given a List<E> list
object, I know of the following ways to loop through all elements:
(给定一个List<E> list
对象,我知道以下遍历所有元素的方式:)
Basic for loop (of course, there're equivalent while
/ do while
loops as well) (基本的for 循环 (当然, while
/ do while
循环也等效))
// Not recommended (see below)!
for (int i = 0; i < list.size(); i++) {
E element = list.get(i);
// 1 - can call methods of element
// 2 - can use 'i' to make index-based calls to methods of list
// ...
}
Note: As @amarseillan pointed out, this form is a poor choice for iterating over List
s, because the actual implementation of the get
method may not be as efficient as when using an Iterator
.
(注意:正如@a??marseillan指出的那样,这种形式对于迭代List
是一个糟糕的选择,因为get
方法的实际实现可能不如使用Iterator
时高效。)
LinkedList
implementations must traverse all of the elements preceding i to get the i-th element. (例如, LinkedList
实现必须遍历i之前的所有元素才能获得第i个元素。)
In the above example there's no way for the List
implementation to "save its place" to make future iterations more efficient.
(在上面的示例中, List
实现无法“保存位置”以使将来的迭代更加有效。)
ArrayList
it doesn't really matter, because the complexity/cost of get
is constant time (O(1)) whereas for a LinkedList
is it proportional to the size of the list (O(n)). (对于一个ArrayList
它其实并不重要,因为复杂性/成本get
是恒定的时间(O(1)),而对于LinkedList
是成正比的列表的大小(为O(n))。)
For more information about the computational complexity of the built-in Collections
implementations, check out this question .
(有关内置Collections
实现的计算复杂度的更多信息,请查看此问题 。)
Enhanced for loop (nicely explained in this question ) (增强了for循环 ( 此问题对此做了很好的解释))
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() to remove the current element from the list
// ...
}
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() to remove the current element from the list
// 3 - can use iter.add(...) to insert a new element into the list
// between element and iter->next()
// 4 - can use iter.set(...) to replace the current element
// ...
}
Functional Java (功能性Java)
list.stream().map(e -> e + 1); // Can apply a transformation function for e
Iterable.forEach , Stream.forEach , ... (Iterable.forEach , Stream.forEach ,...)
(A map method from Java 8's Stream API (see @i_am_zero's answer).)
((来自Java 8的Stream API的map方法(请参阅@i_am_zero的答案)。))
In Java 8 collection classes that implement Iterable
(for example, all List
s) now have a forEach
method, which can be used instead of the for loop statement demonstrated above.
(在实现Iterable
Java 8集合类(例如,所有List
)中,现在具有forEach
方法,可以使用该方法代替上面演示的for循环语句 。)
((这是另一个可以很好比较的问题。))
Arrays.asList(1,2,3,4).forEach(System.out::println);
// 1 - can call methods of an element
// 2 - would need reference to containing object to remove an item
// (TODO: someone please confirm / deny this)
// 3 - functionally separates iteration from the action
// being performed with each item.
Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
// Same capabilities as above plus potentially greater
// utilization of parallelism
// (caution: consequently, order of execution is not guaranteed,
// see [Stream.forEachOrdered][stream-foreach-ordered] for more
// information about this).
What other ways are there, if any?
(还有什么其他方式(如果有)?)
(BTW, my interest does not stem at all from a desire to optimize performance ; I just want to know what forms are available to me as a developer.)
((顺便说一句,我的兴趣根本不是出于优化性能的愿望;我只是想知道开发人员可以使用哪些形式。))
ask by iX3 translate from so