Incrementing counter in Stream foreach Java 8

Depends on where you want to increment.

Either

userList.stream()
        .map(user -> {
               counter.getAndIncrement();
               return new Foo(getName(user), getId(user));
            })
        .forEach(fooList::add);

or

userList.stream()
        .map(user -> new Foo(getName(user), getId(user)))
        .forEach(foo -> {
            fooList.add(foo);
            counter.getAndIncrement();
        });

We can use incrementAndGet method of Atomic Integer.

  AtomicInteger count=new AtomicInteger(0);

  list.forEach(System.out.println(count.incrementAndGet());

can also be done using Stream.peek()

userList.stream()
    .map(user -> new Foo(getName(user), getId(user)))
    .peek(u -> counter.getAndIncrement())
    .forEach(fooList::add);

how about using

java.util.concurrent.atomic.AtomicInteger

example:

AtomicInteger index = new AtomicInteger();

            actionList.forEach(action -> {
                   index.getAndIncrement();
            });