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:
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Path path
= Paths.get( "D:\\eclipse\\p2"
+ "\\org\\eclipse\\equinox\\p2\\core"
+ "\\cache\\binary" );
Iterator<Path> elements
= path.iterator();
System.out.println( "The iterator values are: " );
while (elements.hasNext()) {
System.out.println(elements.next());
}
}
}
|
Output:
Program 2:
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Path path
= Paths.get( "D:\\Workspace"
+ "\\nEclipseWork"
+ "\\GFG\\bin\\defaultpackage" );
System.out.println( "Original Path:"
+ path);
Iterator<Path> elements
= path.iterator();
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()
Last Updated :
30 Jul, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...