当我使用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];
}
}发布于 2016-07-25 20:54:02
取决于您要递增的位置。
或者
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();
});发布于 2020-08-03 01:46:43
我们可以使用原子整数的incrementAndGet方法。
AtomicInteger count=new AtomicInteger(0);
list.forEach(System.out.println(count.incrementAndGet());发布于 2019-10-01 21:32:21
也可以使用Stream.peek()
userList.stream()
.map(user -> new Foo(getName(user), getId(user)))
.peek(u -> counter.getAndIncrement())
.forEach(fooList::add);https://stackoverflow.com/questions/38568129
复制相似问题