Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing counter in Stream foreach Java 8

Tags:

java

I'd like to increment a counter which is an AtomicInteger as I loop through using foreach

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]; } } 
like image 602
Damien-Amen Avatar asked Jul 25 '16 12:07

Damien-Amen


People also ask

How do I add a counter in forEach loop?

Define an integer outside of the loop, and increment it inside of your loop. Use a for loop instead of foreach, which has a count for you: for(int i = 0; i < array. length; i++) { var item = array[i]; Console.

Can we increment a variable inside forEach lambda?

Let's say, we have a list of integers and we want to know the number of integers that are greater than 50 using a forEach loop and lambda expression. We can not declare an integer variable and increment it inside the loop after checking the color or each ball since it will be an error.

Is there a way to access an iteration counter in Java for each loop?

Adding a Counter to forEach with Stream Let's try to convert that into an operation that includes the counter. This function returns a new lambda. That lambda uses the AtomicInteger object to keep track of the counter during iteration. The getAndIncrement function is called every time there's a new item.

Which is faster forEach or stream in Java?

parallel foreach() Works on multithreading concept: The only difference between stream(). forEach() and parallel foreach() is the multithreading feature given in the parallel forEach(). This is way faster that foreach() and stream.


1 Answers

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();         }); 
like image 157
bradimus Avatar answered Sep 18 '22 15:09

bradimus