Archives: Iterator

Java – List Iterate Example

[code lang=”java”]import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class ArrayToList {

public static void main(String[] argv) {

String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" };

// convert array to list
List<String> lList = Arrays.asList(sArray);

// iterator loop
System.out.println("#1 iterator");
Iterator<String> iterator = lList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

// for loop
System.out.println("#2 for");
for (int i = 0; i &lt; lList.size(); i++) {
System.out.println(lList.get(i));
}

// for loop advance
System.out.println("#3 for advance");
for (String temp : lList) {
System.out.println(temp);
}

// while loop
System.out.println("#4 while");
int j = 0;
while (j < lList.size()) {
System.out.println(lList.get(j));
j++;
}
}

}[/code]


Java – NavigableSet Example

[code lang=”java”]import java.util.Arrays;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetDemo {

public static void main(String[] args) {

NavigableSet<String> navigableSet = new TreeSet<String>(Arrays.asList("X", "B", "A", "Z", "T"));

Iterator<String> iterator = navigableSet.descendingIterator();

System.out.println("Original Set :");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

iterator = navigableSet.iterator();

System.out.println("Sorted Navigable Set :");

while (iterator.hasNext()) {
System.out.println(iterator.next());
}

System.out.printf("Head Set : %s.%n", navigableSet.headSet("X"));

System.out.printf("Tail Set : %s.%n", navigableSet.tailSet("T", false));

System.out.printf("Sub Set : %s.%n", navigableSet.subSet("B", true, "X", true));

System.out.printf("Last Element : %s%n", navigableSet.last());

System.out.printf("First Element : %s%n", navigableSet.first());

System.out.printf("Reverse Set : %s%n", navigableSet.descendingSet());

System.out.printf("Original Set : %s%n", navigableSet);

}

}[/code]
Output:

Original Set :
Z
X
T
B
A
Sorted Navigable Set :
A
B
T
X
Z
Head Set : [A, B, T].
Tail Set : [X, Z].
Sub Set : [B, T, X].
Last Element : Z
First Element : A
Reverse Set : [Z, X, T, B, A]
Original Set : [A, B, T, X, Z]