2

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?

tobias_k
  • 81,265
  • 12
  • 120
  • 179
k13i
  • 4,011
  • 3
  • 35
  • 63

3 Answers3

7

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.

Daniel Dietrich
  • 2,262
  • 20
  • 25
0

If you want access to the index, simply use normal for loop and List.get(ix).

jokster
  • 577
  • 5
  • 14
  • 1
    Thanks, I just fought that there is more functional, declarative way to achieve the same goal. – k13i Aug 03 '18 at 09:06
0

JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features. This library also support simple iterate over collection.

   Figure figure = new Rectangle();    

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });