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, 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.

    .map((value, index) -> index)//this is wrong

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;

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

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