Java Path iterator() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

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 */ }
CallWhat 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

ParameterDescription
(none)No arguments.

Return Value

Return ValueDescription
Iterator<Path>Yields getNameCount() elements; none for a root-only path such as /.

Compare with Similar Methods

Other ways to visit the parts of a path:

MethodHow it differs
getName(int)Random access by index instead of a sequence.
getNameCount()How many elements the iterator will return.
Files.walk()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");
    }
}

How It Works

  1. Ask, then take. hasNext() reports whether another element is left and next() returns it, so the loop ends cleanly after song.mp3.
  2. From the root outward. The order matches the indexes of getName: home first, the file name last.
  3. 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());
        }
    }
}

How It Works

  1. 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.
  2. 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.
  3. 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().

Java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;

public class PathIteratorElements {
    public static void main(String[] args) {
        Path p = Paths.get("docs/2026/plan.txt");
        Iterator<Path> it = p.iterator();
        Path first = it.next();
        System.out.println("first.equals(\"docs\"):            " + first.equals("docs"));
        System.out.println("first.toString().equals(\"docs\"): " + first.toString().equals("docs"));
        try {
            it.remove();
        } catch (UnsupportedOperationException e) {
            System.out.println("remove() -> " + e.getClass().getSimpleName());
        }
        it.next();
        it.next();
        try {
            it.next();
        } catch (RuntimeException e) {
            System.out.println("fourth next() -> " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. 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.
  2. Paths cannot be edited. A Path is immutable, so its iterator does not support remove() and throws UnsupportedOperationException.
  3. 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.

Next: Path.normalize()

Remove redundant "." and resolvable ".." name elements from a path.

normalize() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful