Search code examples
javaenumerate

How to enumerate (add indices) to a List-like collection in Java


Note: I am not referring to the java enum/enumeration but rather how to associate the ordinal/index of each element in a collection with the element. I am looking for the equivalent of :

scala :

(1 to 10).zipWithIndex.foreach{ case (obj,i) =>  println(s"Obj[$i]=$obj") }obj.length}

python :

for i,obj in enumerate(range(1,11)):   
   print(f"obj[{i}]={str(obj)}")

javascript :

var myList= [...Array(10)].map((_,i) => 1+i)
myList.forEach( (obj,i) => console.log(`obj[${i}]=${obj}`))

It does not appear that java has a perfect/simple analog? Do we need to use the somewhat awkward manual zip of lists like in this question? How to zip two Java Lists ? What might be the most concise way to associate indices with the list elements?


Solution

  • List may be converted into a map with indexes as keys like this:

    IntStream.range(0, list.size())
             .boxed()
             .collect(Collectors.toMap(i -> i, i -> list.get(i)));
    

    If Map is not needed, Stream API provides IntStream::forEach method:

    IntStream.range(0, list.size())
             .forEach(i -> System.out.println(i + " -> " + list.get(i)));
    

    Also it is possible to use Iterable::forEach and count the index separately (e.g. with AtomicInteger):

    AtomicInteger index = new AtomicInteger(0);
    list.forEach(x -> System.out.println(index.getAndIncrement() + " -> " + x));