java中for循环中计数器_是否有办法在Java中为每个循环访问一个迭代计数器?

使用

兰姆达斯

功能接口

在里面

爪哇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);

}

}

}

图书馆将开始出现来做这些事情,或者你可以自己滚动。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值