Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

Incrementing counter in Stream foreach Java 8

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];
}
}
question from:https://stackoverflow.com/questions/38568129/incrementing-counter-in-stream-foreach-java-8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...