Search code examples
javalambdacollectionsforeachvavr

Iterate over list with indices in vavr


I'm using collections from vavr library. I have a list of elements defined like this:

List<Integer> integers = List.of(1, 2, 3);

How to iterate over elements of the list and have an access to the indices at the same time? In Groovy there is a method eachWithIndex. I'm looking for something similar in vavr. I'd like to use it like this:

integers.eachWithIndex((int element, int index) -> {
     System.out.println("index = " + index + " element = " + element);
})

How can I achieve this in vavr?


Solution

  • Vavr has an API similar to Scala. The Vavr collections (aka traversables) have a method called zipWithIndex(). It returns a new collection, which consists of tuples of elements and indices.

    Additionally, using an Iterator saves us new collection instances.

    final List<Integer> integers = List.of(1, 2, 3);
    
    integers.iterator().zipWithIndex().forEach(t ->
        System.out.println("index = " + t._1 + " element = " + t._2)
    );
    

    However, I see that creating a new collection is not as efficient as the Kotlin solution, especially when all information is already in place (elements and indices). I like the idea of adding a new method forEachWithIndex to Vavr's collections that acts like in Kotlin.

    Update: We could add forEachWithIndex(ObjIntConsumer<? super T>) to Vavr's Traversable. It is more than just a shortcut for iterator().zipWithIndex().forEach(Consumer<Tuple2<T, Integer>>) because it does not create Tuple2 instances during iteration.

    Update: I just added forEachWithIndex to Vavr. It will be included in the next release.

    Disclaimer: I'm the creator of Vavr.