我想在使用 foreach
循环时增加一个 counter
,它是一个 AtomicInteger
public class ConstructorTest {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger(0);
List<Foo> fooList = Collections.synchronizedList(new ArrayList<Foo>());
List<String> userList = Collections.synchronizedList(new ArrayList<String>());
userList.add("username1_id1");
userList.add("username2_id2");
userList.stream().map(user -> new Foo(getName(user), getId(user))).forEach(fooList::add);
//how do I increment the counter in the above loop
fooList.forEach(user -> System.out.println(user.getName() + " " + user.getId()));
}
private static String getName(String user) {
return user.split("_")[0];
}
private static String getId(String user) {
return user.split("_")[1];
}
}
最佳答案
取决于你想增加的地方。
要么
userList.stream()
.map(user -> {
counter.getAndIncrement();
return new Foo(getName(user), getId(user));
})
.forEach(fooList::add);
或
userList.stream()
.map(user -> new Foo(getName(user), getId(user)))
.forEach(foo -> {
fooList.add(foo);
counter.getAndIncrement();
});
关于java - Stream foreach Java 8 中的递增计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38568129/