Java : Iterable with Examples
Iterable (Java SE 22 & JDK 22) with Examples.
You will find code examples on most Iterable<T> methods.
Summary
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)
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 ()
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 ()
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