在Java 8中使用lambda表达式和函数接口可以创建新的循环抽象。我可以通过索引和集合大小遍历集合:
List<String> 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<T> {
void accept(T t, int i, int n);
}
public static <T> void forEach(Collection<T> collection,
LoopWithIndexAndSizeConsumer<T> 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 <T> void forEachHeadTail(Collection<T> collection,
Consumer<T> headFunc,
Consumer<T> tailFunc) {
int index = 0;
for (T object : collection){
if (index++ == 0){
headFunc.accept(object);
}
else{
tailFunc.accept(object);
}
}
}
会出现一些库来完成这些事情,或者你可以自己开发。
Type var = null; for (var : set) dosomething; if (var != null) then ...
- Val