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
688 views
in Technique[技术] by (71.8m points)

lambda - How to map elements of the list to their indices using Java 8 streams?

Having a list of strings, I need to construct a list of objects which are effectively pairs (string, its position in the list). Currently I have such code using google collections:

public Robots(List<String> names) {
    ImmutableList.Builder<Robot> builder = ImmutableList.builder();
    for (int i = 0; i < names.size(); i++) {
        builder.add(new Robot(i, names.get(i)));
    }
    this.list = builder.build();
}

I would like to do this using Java 8 streams. If there was no index, I could just do:

public Robots(List<String> names) {
    this.list = names.stream()
            .map(Robot::new) // no index here
            .collect(collectingAndThen(
                    Collectors.toList(),
                    Collections::unmodifiableList
            ));
}

To get the index, I would have to do something like this:

public Robots(List<String> names) {
    AtomicInteger integer = new AtomicInteger(0);
    this.list = names.stream()
            .map(string -> new Robot(integer.getAndIncrement(), string))
            .collect(collectingAndThen(
                    Collectors.toList(),
                    Collections::unmodifiableList
            ));
}

However, the documentation says that mapping function should be stateless, but the AtomicInteger is effectively its state.

Is there a way to map elements of the sequential stream to their positions in the stream?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could do something like this:

public Robots(List<String> names) {
    this.list = IntStream.range(0, names.size())
                         .mapToObj(i -> new Robot(i, names.get(i)))
                         .collect(collectingAndThen(toList(), Collections::unmodifiableList));
}

However it may not be as efficient depending on the underlying implementation of the list. You could grab an iterator from the IntStream; then calling next() in the mapToObj.

As an alternative, the proton-pack library defines the zipWithIndex functionality for streams:

 this.list = StreamUtils.zipWithIndex(names.stream())
                        .map(i -> new Robot(i.getIndex(), i.getValue()))
                        .collect(collectingAndThen(toList(), Collections::unmodifiableList));

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

...