Incrementing counter in Stream foreach Java 8

We can use incrementAndGet method of Atomic Integer.

  AtomicInteger count=new AtomicInteger(0);

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

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();
        });

Tags:

Java