# Iterable接口分析

Implementing this interface allows an object to be the target of the "for-each loop" statement.

接口作用:实现此接口允许对象成为“for each loop”语句的目标。

参数类型: –迭代器返回的元素类型

# 定义接口

public interface Iterable<T> {

}
1
2
3

# 接口行为

Iterator表示:迭代器

Returns an iterator over elements of type T.

作用:返回T类型元素的迭代器。

返回:一个迭代器

    Iterator<T> iterator();
1

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

对Iterable的每个元素执行给定的操作,直到所有元素都已处理或该操作抛出异常。除非实现类另有规定,否则操作将按迭代顺序执行(如果指定了迭代顺序)。操作引发的异常会被转发给调用者。

Params: action – The action to be performed for each element

action–每个元素要执行的操作

Throws: NullPointerException – if the specified action is null

NullPointerException–如果指定的操作为null

Implementation The default implementation behaves as if:

实现默认实现的行为如下:

Requirements(需求):

    for (T t : this)     
        action. accept(t);
1
2

Since: 1.8

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
1
2
3
4
5
6

Creates a Spliterator over the elements described by this Iterable. Returns:返回 a Spliterator over the elements described by this Iterable.

Implementation Requirements: The default implementation creates an early-binding spliterator from the iterable's Iterator. The spliterator inherits the fail-fast properties of the iterable's iterator.

Implementation Note: The default implementation should usually be overridden. The spliterator returned by the default implementation has poor splitting capabilities, is unsized, and does not report any spliterator characteristics. Implementing classes can nearly always provide a better implementation.

Since: 1.8

创建一个Spliterator,用于遍历此Iterable描述的元素。 返回:一个Spliterator,用于遍历此Iterable描述的元素。

实现要求:默认实现从iterable的Iterator创建一个早期绑定的spliterator。该spliterator继承iterable的iterator的快速失败属性。

实现备注:默认实现通常应该被重写。默认实现返回的spliterator分割能力差,大小未知,并且不报告任何spliterator特性。实现类几乎总是能提供更好的实现。

自:1.8

    default Spliterator<T> spliterator() {
        return Spliterators.spliteratorUnknownSize(iterator(), 0);
    }
1
2
3

# spliterator是什么

spliterator可是由

split - terator二个词组成。

它比传统的 Iterator 更强大,主要有两个核心功能:

  1. 遍历元素:和 Iterator 一样,可以逐个访问集合中的元素。
  2. 拆分数据:这是其关键特性。它可以将自身代表的数据源(如集合)的一部分“拆分”出去,形成一个新的 Spliterator。这两个 Spliterator 可以被并行处理,这是Java 8+中并行流(parallelStream)实现高性能并行计算的基石。

# spliterator举例说明理解

想象一下你有一本很厚的书(一个大数据集合)需要翻译。

  • 传统的 Iterator 就像你一个人从头到尾一页一页地翻译。
  • Spliterator 则允许你把书拆分成几个大致相等的章节,分给多个翻译人员(多个线程)同时工作,最后再把结果合并起来,从而极大提高效率。

结论:在中文交流中,请直接使用 “Spliterator” 这个术语,并将其理解为一个用于支持高效并行遍历和处理的“可拆分迭代器”。

# 关联到其它接口


import java.util.Spliterator;

import java.util.Spliterators;

// 消费者接口
import java.util.function.Consumer;
1
2
3
4
5
6
7
Last Updated: 4/3/2026, 6:47:37 AM