-1

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?

StephenBoesch
  • 46,509
  • 64
  • 237
  • 432
  • Lists elements do have indices. I feel like you're asking something more than that, but I don't really understand what you're asking. – Charlie Armstrong Mar 16 '21 at 20:06
  • @CharlieArmstrong Lists do have indices but I mentioned `Collections` in an attempt to indicate any iterable container including ones not providing indices. – StephenBoesch Mar 16 '21 at 20:08
  • Ah, I see what you mean now. AFAIK there's no easy way to do that in Java. If it were me I would just start off with an IntStream and index into the collection from there, as the duplicate targets suggest. Interesting concept, though, as a Java programmer I've never heard of "zipping" collections. – Charlie Armstrong Mar 16 '21 at 20:15

1 Answers1

3

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));
Alex Rudenko
  • 15,656
  • 9
  • 13
  • 33
  • Presuming we want a `forEach` on the `(index, element)` tuple than what is the most concise version? Your `Map` has its uses but is partially extraneous for that purpose given we do not care /need to retain any `Map` afterwards. – StephenBoesch Mar 16 '21 at 20:12
  • (after your update): Yes that's what I am looking for – StephenBoesch Mar 16 '21 at 20:19