CodeDevStack

Using indices inside a Java stream map

February 06, 2020

Coming from Javascript, getting the index of a value inside a mapping function is pretty simple

someArray.map((value, index) => {
    console.log(index);//0,1,2,3, etc
});

But when I had to do something similar using Java, I found out that streams don’t give you access to indices.

someList.toStream()
    .map((value, index) -> index)//this is wrong
    .collect(Collectors.toList());

The code above is just wrong.

A quick workaround, if you need to get the index of a value, is to stream indices!

List<myObject> myList;

IntStream
    .range(0, myList.size())
    .mapToObj(index -> {
        myObject value = myList.get(index);
        
        //here we can do whatever we want with the index and value
        log.info(value.toString(), index;
        myObject nextValue = myList.get(index + 1);//get the next value in the list
        return value;
    })
    .collect(Collectors.toList());

So there you have it, a quick and simple workaround to use map() and have access to indices.