使用
兰姆达斯
和
功能接口
在里面
爪哇8
使创建新的循环抽象成为可能。我可以循环使用索引和集合大小的集合:
List strings = Arrays.asList("one", "two","three","four");
forEach(strings, (x, i, n) -> System.out.println("" + (i+1) + "/"+n+": " + x));
输出:
1/4: one
2/4: two
3/4: three
4/4: four
我执行为:
@FunctionalInterface
public interface LoopWithIndexAndSizeConsumer {
void accept(T t, int i, int n);
}
public static void forEach(Collection collection,
LoopWithIndexAndSizeConsumer consumer) {
int index = 0;
for (T object : collection){
consumer.accept(object, index++, collection.size());
}
}
可能性是无限的。例如,我创建了一个抽象,它只对第一个元素使用一个特殊的函数:
forEachHeadTail(strings,
(head) -> System.out.print(head),
(tail) -> System.out.print(","+tail));
正确打印逗号分隔列表:
one,two,three,four
我执行为:
public static void forEachHeadTail(Collection collection,
Consumer headFunc,
Consumer tailFunc) {
int index = 0;
for (T object : collection){
if (index++ == 0){
headFunc.accept(object);
}
else{
tailFunc.accept(object);
}
}
}
图书馆将开始出现来做这些事情,或者你可以自己滚动。