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]; } }
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.
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.
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.
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.
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With