对于Java语言来说,我尝试熟悉所有的方法,以便可以遍历列表以及每个方法的优缺点。
给定一个List<E> list对象,我知道以下方法遍历所有元素:
基本的 循环(当然,也有相同的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 // ...}注意:这个形式对于迭代Lists来说是一个糟糕的选择,因为这个get方法的实际实现可能不如使用一个方法的效率Iterator。例如,LinkedList实现必须遍历i之前的所有元素才能获得第i个元素。在上面的例子中,List实现没有办法“保存它的位置”,以使未来的迭代更有效率。对于一个ArrayList它并不重要,因为复杂性/成本get是恒定的时间(O(1)),而对于一个LinkedList是成正比的列表(O(n))的大小。
增强for循环(在这个问题很好地解释)
for (E element : list) { // 1 - can call methods of element // ...}迭代器
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 // ...}编辑:添加ListIterato
的ListIterato
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 // ...}编辑:添加“功能风格”的解决方案
功能性的Java
list.stream().map(e -> e + 1); // can apply a transformation function for e编辑:添加从Java 8的Stream API的地图方法
Iterable.forEach,Stream.forEach,...在实现的Java 8集合类Iterable(例如所有Lists)中,现在有一个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 greate// utilization of parallelism// (caution: consequently, order of execution is not guaranteed,// see [Stream.forEachOrdered][stream-foreach-ordered] for more// information about this.)还有什么其他的方式,如果有的话?
相似问题