1. java中的Iterable & Iterator?
Q1: What are the difference between Iterator VS Iterable?
A1: The “Iterable” was introduced to be able to use in the ‘foreach’ loop. A class implementing the Iterable interface can be iterated over.
实现了 Iterable接口的类可以用于增强的for循环中国年,即:for-each语句。
2. for-each 和 iterable
foreach->iterator()->next()
3. Iterator()
迭代器Iterator是这样一类东西:它管理可迭代对象的迭代访问。它维护一个当前访问迭代的状态,而且知道下一个元素的位置以及如何得到它。
Q2: How to get an Iterable in java 8 to be used in a foreach loop?
A2: In java 8, call the double ‘::’ notation as below, you can get an iterable from the Stream.
package com.fqy.blog;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class MyFileReader {
public static void main(String[] args) {
Path file = null;
try {
// read from the classpath
URL url = MyFileReader.class.getResource("readme.txt");
file = Paths.get(url.toURI());
// Java 8: Stream class
Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8);
for (String line : (Iterable<String>) lines::iterator) {
System.out.println("read=" + line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Running result:
read=You can rewind an Iterable by getting a new iterator() from the Iterable.
read=But an Iterator only has the next() method.
read=So, an Iterable is handy if you want to traverse the elements more than once.
read=
read=Q2. How do you get an Iterable in Java 8 to be used in a foreach loop?
read=A2. In Java 8, when you call the double “::” notation as shown below, you get an Iterable from the Stream.
4. Using both Iterable and Iterator
package com.fqy.blog;
import java.util.Iterator;
class MyIterable<T> implements Iterable<T> {
public T[] arr = null;
public MyIterable(T[] arr) {
this.arr = arr;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
@Override
public boolean hasNext() {
if (index < arr.length)
return true;
return false;
}
@Override
public T next() {
System.out.println("Invoking next: ");
if (this.hasNext())
return arr[index++];
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
public class IterableWithIterator {
public static void main(String[] args) {
String[] arr = { "Java", "Oracle", "Operation System", "Spring MVC" };
MyIterable<String> myIterable = new MyIterable<>(arr);
for (String str : myIterable)
System.out.println(str);
}
}
//Running result:
Invoking next:
Java
Invoking next:
Oracle
Invoking next:
Operation System
Invoking next:
Spring MVC