package t20211225;
import java.util.*;
/**
* @Author: DengJia
* @Date: 2021/12/26 10:04
* @Description: 顺序迭代、逆序迭代、乱序迭代
*/
public class IterableClass implements Iterable<String> {
protected String[] words = ("1 2 3 4 5 6 7 8 9 0").split(" ");
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < words.length;
}
@Override
public String next() {
return words[index++];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
MultiIterableClass mic = new MultiIterableClass();
System.out.print("顺序迭代:");
for (String s : mic) {
System.out.print(s + " ");
}
System.out.print("\n逆序迭代:");
for (String s : mic.reversed()) {
System.out.print(s + " ");
}
System.out.print("\n乱序迭代:");
for (String s : mic.randomized()) {
System.out.print(s + " ");
}
}
}
class MultiIterableClass extends IterableClass {
public Iterable<String> reversed() {
return () -> new Iterator<String>() {
int current = words.length - 1;
@Override
public boolean hasNext() {
return current > -1;
}
@Override
public String next() {
return words[current--];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Iterable<String> randomized() {
return () -> {
// 洗牌
List<String> shuffled = new ArrayList<>(Arrays.asList(words));
Collections.shuffle(shuffled, new Random(47));
return shuffled.iterator();
};
}
}
顺序迭代:1 2 3 4 5 6 7 8 9 0
逆序迭代:0 9 8 7 6 5 4 3 2 1
乱序迭代:4 6 3 1 8 7 2 5 0 9