List 的遍历总结——Java 8 新思路

版权声明: https://blog.csdn.net/ShadowySpirits/article/details/79633885

Java 8 之前的 List 遍历


使用 foreach:

这种方式的本质就是调用迭代器,区别在于不能使用remove

for (Element element : elements) {......}


需要使用数组下标:

int size = elements.size();
for(int i = 0; i < size ;i++) {......}

注意:请避免使用 for(int i = 0; i < list.size();i++) 这种形式,以免多次调用 List.size() 浪费资源

需要删除List中的某些元素:

使用迭代器:此种方法可以避免 for 循环中多次删除产生的下标越界问题以及在 foreach 中调用 list.remove() 时抛出的 ConcurrentModificationException

Iterator<String> it = list.iterator();
while(it.hasNext()){
    String x = it.next();
    if(x.equals("del")){
        it.remove();
    }
}



Java 8 中的新增方法


使用 stream 和 lambda 表达式配合:

list.stream()
    .filter(p->p.equals("filter"))
    .forEach(System.out::println);


Stream 操作分类

中间操作
(Intermediate operations)
无状态(Stateless) unordered() filter() map() mapToInt()
mapToLong() mapToDouble() flatMap()
flatMapToInt() flatMapToLong() flatMapToDouble() peek()
有状态
(Stateful)
distinct() sorted() sorted() limit() skip()
结束操作
(Terminal operations)
非短路操作 forEach() forEachOrdered() toArray() reduce() collect() max() min() count()
短路操作
(short-circuiting)
anyMatch() allMatch() noneMatch() findFirst() findAny()

Stream 中的操作可以分为两大类:中间操作与结束操作,中间操作只是对操作进行了记录,只有结束操作才会触发实际的计算(即惰性求值),这也是Stream在迭代大集合时高效的原因之一。中间操作又可以分为无状态(Stateless)操作与有状态(Stateful)操作,前者是指元素的处理不受之前元素的影响;后者是指该操作只有拿到所有元素之后才能继续下去。结束操作又可以分为短路与非短路操作,这个应该很好理解,前者是指遇到某些符合条件的元素就可以得到最终结果;而后者是指必须处理所有元素才能得到最终结果。 (原文链接

猜你喜欢

转载自blog.csdn.net/ShadowySpirits/article/details/79633885