Stream foreach Java 8 中的递增计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38568129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:25:50  来源:igfitidea点击:

Incrementing counter in Stream foreach Java 8

java

提问by Damien-Amen

I'd like to increment a counterwhich is an AtomicIntegeras I loop through using foreach

我想增加一个counter是一个AtomicInteger,因为我通过循环使用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];
}
}

采纳答案by bradimus

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

回答by OldCurmudgeon

You can change it to an anonymous class:

您可以将其更改为匿名类:

        userList.stream().map(new Function<String, Object>() {
            @Override
            public Object apply(String user) {
                counter.addAndGet(1);
                return new Foo(getName(user), getId(user));
            }
        }).forEach(fooList::add);

Remember to make counterfinal.

记得做counterfinal

回答by SIVA KUMAR

can also be done using Stream.peek()

也可以使用 Stream.peek() 完成

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

回答by Tiago Medici

how about using

怎么样使用

java.util.concurrent.atomic.AtomicInteger

example:

例子:

AtomicInteger index = new AtomicInteger();

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