Home > OS >  Parallel FOR Iteration using Generics and Iterables on Java
Parallel FOR Iteration using Generics and Iterables on Java

Time:09-30

I was wondering if it's possible to create a parallel for iterator , kind of what Python does.

An Example on python would be :

foo = (1, 2, 3)
bar = (4, 5, 6)

for (f, b) in some_iterator(foo, bar):
print("f: ", f, "; b: ", b)

I don't necessarily want to be true parallel or use threads and all , just have a class to give you the idea that is running tu lists on parallel.

My idea was to use generics and iterables, let me show you my unfinished code just to explain my idea:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class ParallelList<T> implements Iterable<List<T>> {

private final List<List<T>> lists;

public ParallelList(List<T>... lists) {
    this.lists = new ArrayList<List<T>>(lists.length);
    this.lists.addAll(Arrays.asList(lists));
}

public Iterator<List<T>> iterator() {
    return new Iterator<List<T>>() {
        private int loc = 0;

        public boolean hasNext() {
            boolean hasNext = false;
            for (List<T> list : lists) {
                hasNext |= (loc < list.size());
            }
            return hasNext;
        }

        public List<T> next() {
            List<T> vals = new ArrayList<T>(lists.size());
            for (int i=0; i<lists.size(); i  ) {
                vals.add(loc < lists.get(i).size() ? lists.get(i).get(loc) : null);
            }
            loc  ;
            return vals;
        }

        public void remove() {
            for (List<T> list : lists) {
                if (loc < list.size()) {
                    list.remove(loc);
                }
            }
        }
    };
}

}

My idea is to use iterables to do that and then use a FOR upon those iterables inside the class to simulate the parallel FOR, but I'm stuck on the FOR part , I have no idea how to create a "dynamic" for for all the iterables I could get , or how to do it. What are your suggestions to accomplish that ?

CodePudding user response:

This operation is usually called zip. If you want to check one implementation, the JOOL library provides a quite nice Seq.zip() method which zips the elements of two collections in tuples.

For example

Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"));

returns a

Seq.of(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"));

I miss how simple Kotlin makes these operations :D.

  • Related