Stream mapWithIndex Method Provided by the Java Guava Library
This page explains the mapWithIndex method in the Guava library.
Providing an index in Stream map
The map function available in Java Stream cannot receive an index.
Starting with version 21, guava provides mapWithIndex, a map for Stream that can receive an index.
Let’s look at it with a simple example.
package com.devkuma.guava.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.google.common.collect.Streams;
public class MapWithIndex {
public static void main(String[] args) {
List<String> results = Streams.mapWithIndex(
Arrays.asList("a", "b", "c").stream(),
(str, index) -> str + ":" + index
).collect(Collectors.toList());
results.stream().forEach(r -> {
System.out.println(r);
});
}
}
Execution result:
a:0
b:1
c:2
The first argument specifies the collection or array to turn into a Stream, and the second argument specifies a lambda expression.