Incrementing counter in Stream foreach Java 8

We Are Going To Discuss About Incrementing counter in Stream foreach Java 8. So lets Start this Java Article.

Incrementing counter in Stream foreach Java 8

  1. 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());

  2. 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());

Solution 1

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

Original Author bradimus Of This Content

Solution 2

We can use incrementAndGet method of Atomic Integer.

  AtomicInteger count=new AtomicInteger(0);

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

Original Author Supreet Singh Of This Content

Solution 3

can also be done using Stream.peek()

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

Original Author SIVA KUMAR Of This Content

Solution 4

how about using

java.util.concurrent.atomic.AtomicInteger

example:

AtomicInteger index = new AtomicInteger();

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

Original Author Tiago Medici Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment