Related Articles

Related Articles

Path iterator() method in Java with Examples
  • 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:



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()

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :