-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJavaIterator.java
More file actions
49 lines (41 loc) · 1.42 KB
/
JavaIterator.java
File metadata and controls
49 lines (41 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package JavaBasic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class JavaIterator {
public static void main(String[] args) {
List<String> l = new ArrayList<>();
l.addAll(List.of("a", "b", "c"));
Iterator<String> it = l.iterator();
// can't do the follwing, it only can be called after .next()
// it.remove();
while (it.hasNext()) {
String next = it.next();
System.out.println(next);
if (next.equals("b")) {
it.remove();
}
}
it.forEachRemaining(System.out::println);
// will not getting to here, as previous already consumed it ?
while (it.hasNext()) {
System.out.println(it.next() + " ? ");
}
//
ListIterator<String> listIterator = l.listIterator();
while (listIterator.hasNext()) {
String nextWithIndex = l.get(listIterator.nextIndex());
String next = listIterator.next();
if ("REPLACE ME".equals(next)) {
listIterator.set("REPLACED");
}
}
listIterator.add("NEW");
while (listIterator.hasPrevious()) {
String previousWithIndex = l.get(listIterator.previousIndex());
String previous = listIterator.previous();
System.out.println(previous);
}
}
}