Java : Iterable with Examples

Iterable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Iterable<T> methods.


Summary

Implementing this interface allows an object to be the target of the enhanced for statement (sometimes called the "for-each loop" statement).

Class diagram

public class Sample implements Iterable<String> {
    private static final String[] VALUES = {"aaa", "bbb", "ccc"};
    private int index;

    @Override
    public Iterator<String> iterator() {
        return new Iterator<>() {
            @Override
            public boolean hasNext() {
                return VALUES.length != index;
            }

            @Override
            public String next() {
                final var value = VALUES[index];
                index++;
                return value;
            }
        };
    }
}
final var sample = new Sample();
for (final var s : sample) {
    System.out.println(s);
}

// Result
// ↓
//aaa
//bbb
//ccc

Methods

default void forEach (Consumer<? super T> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

final Iterable<String> it = List.of("aaa", "bbb", "ccc");
System.out.println(it); // [aaa, bbb, ccc]

it.forEach(s -> System.out.println(s));

// Result
// ↓
//aaa
//bbb
//ccc
final Iterable<Path> it = Path.of("dir1", "dir2", "test.txt");
System.out.println(it); // dir1\dir2\test.txt

it.forEach(System.out::println);

// Result
// ↓
//dir1
//dir2
//test.txt

Iterator<T> iterator ()

Returns an iterator over elements of type T.

final Iterable<String> it = List.of("aaa", "bbb", "ccc");
System.out.println(it); // [aaa, bbb, ccc]

final var iterator = it.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

// Result
// ↓
//aaa
//bbb
//ccc

default Spliterator<T> spliterator ()

Creates a Spliterator over the elements described by this Iterable.

final Iterable<String> it = List.of("aaa", "bbb", "ccc", "ddd", "eee");
System.out.println(it); // [aaa, bbb, ccc, ddd, eee]

final var s1 = it.spliterator();
System.out.println("s1 size : " + s1.estimateSize()); // s1 size : 5

final var s2 = s1.trySplit();
System.out.println("s1 size : " + s1.estimateSize()); // s1 size : 3
System.out.println("s2 size : " + s2.estimateSize()); // s2 size : 2

s1.forEachRemaining(System.out::println);

// Result (s1)
// ↓
//ccc
//ddd
//eee

s2.forEachRemaining(System.out::println);

// Result (s2)
// ↓
//aaa
//bbb

Related posts

To top of page