Skip to content
Related Articles

Related Articles

Path iterator() method in Java with Examples

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Jul, 2019

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:




// 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());
        }
    }
}

Output:

Program 2:




// 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());
        }
    }
}

Output:

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!