In Java, path.iterator() returns an Iterator<Path> that visits the name elements of the path in order, starting at the element closest to the root. Because Path extends Iterable<Path>, you can also write for (Path part : path).
The root is not visited. For /home/anna/music/song.mp3 the iterator returns home, anna, music, and song.mp3, each as a one-element Path.
An instance method of the java.nio.file.Path interface, available since Java 7. Call it on a Path object, as in path.iterator(...), after import java.nio.file.Path;.
Syntax
Use the iterator directly or let a for-each loop call it for you:
Java
Iterator<Path> it = path.iterator();
while (it.hasNext()) {
Path part = it.next();
}
for (Path part : path) { /* same elements */ }
Call
What it does
p.iterator()
An Iterator<Path> over the name elements.
for (Path part : p)
For-each loop over the same elements.
part.toString()
One element as a String.
Since Java 7. In Java 11 and later it is a default method of the interface, built on getNameCount() and getName(int).
Library declarations
Java
// java.nio.file.Path (interface), which extends Iterable<Path>
Iterator<Path> iterator()
Parameters
Parameter
Description
(none)
No arguments.
Return Value
Return Value
Description
Iterator<Path>
Yields getNameCount() elements; none for a root-only path such as /.
Visits files and folders on disk, not the names inside one path.
Java Examples
Outputs below are shown for Linux and macOS. On Windows, Java prints \ between names instead of /; the note above each output says when a result really differs.
Example 1 — Visit Each Name with an Explicit Iterator
Call iterator() and use hasNext() and next() to print every element of an absolute path.
Java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
public class PathIteratorBasic {
public static void main(String[] args) {
Path song = Paths.get("/home/anna/music/song.mp3");
Iterator<Path> it = song.iterator();
int count = 0;
while (it.hasNext()) {
Path part = it.next();
System.out.println("-> " + part);
count++;
}
System.out.println(count + " elements, root " + song.getRoot() + " not included");
}
}
Output
Run with java PathIteratorBasic. Shown for Linux and macOS. On Windows the last line shows the root as \; the four elements are the same.
-> home
-> anna
-> music
-> song.mp3
4 elements, root / not included
How It Works
Ask, then take.hasNext() reports whether another element is left and next() returns it, so the loop ends cleanly after song.mp3.
From the root outward. The order matches the indexes of getName: home first, the file name last.
The root stays out. Four elements are counted, and the root / is printed separately with getRoot() because the iterator never returns it.
Example 2 — Skip Files Inside Hidden Folders
A backup tool should ignore anything inside folders such as .git or .cache. A for-each loop checks every element of each path.
Java
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathIteratorHidden {
static boolean insideHidden(Path p) {
for (Path part : p) {
if (part.toString().startsWith(".")) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Path[] files = {Paths.get("shop/.git/config"), Paths.get("shop/src/App.java"),
Paths.get("shop/.cache/img/a.bin"), Paths.get("shop/notes.txt")};
for (Path f : files) {
System.out.println((insideHidden(f) ? "skip " : "backup ") + f.getFileName());
}
}
}
Output
Run with java PathIteratorHidden. The output is the same on Windows, macOS, and Linux.
for-each calls iterator() for you.for (Path part : p) compiles to p.iterator() plus hasNext()/next(), so every name element of the path is checked in turn.
Test the text of one element.part.toString().startsWith(".") looks at a single name, so .git is caught but a dot in the middle of a name, as in notes.txt, is not.
Stop at the first match. The helper returns true as soon as a hidden element appears, so config and a.bin are skipped while the two normal files are backed up.
Example 3 — See That Elements Are Path Objects and Read-Only
Compare an element with a String the wrong and the right way, then try remove() and an extra next().
A Path is not a String.first.equals("docs") compares a Path with a String and is always false; converting with toString() gives the expected true.
Paths cannot be edited. A Path is immutable, so its iterator does not support remove() and throws UnsupportedOperationException.
Three names, three next() calls. After docs, 2026, and plan.txt the iterator is exhausted; the fourth call throws NoSuchElementException, caught here as a RuntimeException.
Frequently Asked Questions
Use a for-each loop, for (Path part : path), or call path.iterator() and use hasNext() and next(). Both visit the name elements in order.
No. Only name elements are returned, so the iterator of / returns nothing and /home/anna returns home and anna.
Each element is a Path with a single name. Call toString() to compare it with a String.
No. Paths are immutable, so remove() throws UnsupportedOperationException. Build a new path with subpath or resolve instead.
No. It only splits the path text into names. To list a folder use Files.list, and to visit a whole tree use Files.walk.