在Java的for-each循环中有办法吗
for(String s : stringArray) {
doSomethingWith(s);
}
找出循环已经被处理的频率?
除了使用老的和众所周知的for(int i=0;I <边界;i++) - loop,是构造
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
在for-each循环中有这样一个计数器的唯一方法是什么?
在Java的for-each循环中有办法吗
for(String s : stringArray) {
doSomethingWith(s);
}
找出循环已经被处理的频率?
除了使用老的和众所周知的for(int i=0;I <边界;i++) - loop,是构造
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
在for-each循环中有这样一个计数器的唯一方法是什么?
当前回答
pax的答案有一个“变体”…: -)
int i = -1;
for(String s : stringArray) {
doSomethingWith(s, ++i);
}
其他回答
在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);
}
}
}
库将开始弹出来做这些事情,或者你可以自己编写。
虽然有很多其他的方法可以达到同样的效果,但我还是将我的方法分享给一些不满意的用户。我正在使用Java 8 IntStream特性。
1. 数组
Object[] obj = {1,2,3,4,5,6,7};
IntStream.range(0, obj.length).forEach(index-> {
System.out.println("index: " + index);
System.out.println("value: " + obj[index]);
});
2. 列表
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");
IntStream.range(0, strings.size()).forEach(index-> {
System.out.println("index: " + index);
System.out.println("value: " + strings.get(index));
});
Sun正在为Java7考虑的一个变化是在foreach循环中提供对内部迭代器的访问。语法将是这样的(如果这是接受的):
for (String str : list : it) {
if (str.length() > 100) {
it.remove();
}
}
这是语法上的甜食,但显然有很多人对这个功能提出了要求。但是在它被批准之前,您必须自己计算迭代次数,或者使用带有Iterator的常规for循环。
pax的答案有一个“变体”…: -)
int i = -1;
for(String s : stringArray) {
doSomethingWith(s, ++i);
}
Java 8引入了Iterable#forEach() / Map#forEach()方法,与“经典的”for-each循环相比,该方法对于许多Collection / Map实现更有效。但是,在这种情况下也不提供索引。这里的技巧是在lambda表达式之外使用AtomicInteger。注意:lambda表达式中使用的变量必须有效为final,这就是为什么我们不能使用普通int类型。
final AtomicInteger indexHolder = new AtomicInteger();
map.forEach((k, v) -> {
final int index = indexHolder.getAndIncrement();
// use the index
});