Path iterator() method in Java with Examples

The iterator() method of java.nio.file.Path used to returns an iterator of the name elements which construct this path.
The first element of this iterator contains the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element of this iterator is the name of the file or directory denoted by this path. The root component is not returned by the iterator.

Syntax:

default Iterator<Path> iterator()

Parameters: This method accepts nothing.It is parameter less method.



Return value: This method returns an iterator over the name elements of this path.

Below programs illustrate iterator() method:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// java.nio.file.Path.iterator() method
  
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of Path
        Path path
            = Paths.get("D:\\eclipse\\p2"
                        + "\\org\\eclipse\\equinox\\p2\\core"
                        + "\\cache\\binary");
  
        // Creating an iterator
        Iterator<Path> elements
            = path.iterator();
  
        // Displaying the values
        System.out.println("The iterator values are: ");
        while (elements.hasNext()) {
            System.out.println(elements.next());
        }
    }
}

chevron_right


Output:

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// java.nio.file.Path.iterator() method
  
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of Path
        Path path
            = Paths.get("D:\\Workspace"
                        + "\\nEclipseWork"
                        + "\\GFG\\bin\\defaultpackage");
  
        System.out.println("Original Path:"
                           + path);
  
        // Creating an iterator
        Iterator<Path> elements
            = path.iterator();
  
        // Displaying the values
        System.out.println("The iterator values are: ");
        while (elements.hasNext()) {
            System.out.println(elements.next());
        }
    }
}

chevron_right


Output:

References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#iterator()



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.